//寫一個函數,將字符串翻轉,翻轉方式如下:“I am a student”反轉成“student a am I”,不借助任何庫函數。
根據參考,我的代碼如下,代碼中要注意二個地方,程序中有註明。
//反轉函數,將"I am a student"轉換成"student a am I"
//第一步是整體反轉成"tneduts a ma I",第二次以空格爲分界線,局部反轉
#include <iostream>
#include <stdio.h>
int main(void)
{
int j,i,flag,begin,end;
j=0;i=0;
char str[] = "i am a good girl";
char temp;
j = strlen(str)-1;
printf("初始的時候string: %s\n",str);
//第一步是進行全盤反轉,將單詞變成"tneduts a ma I"
while(j>i)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
--j;
++i;
}
printf("全部反轉後的結果string: %s\n",str);
//第二步進行局部反轉,以空格爲分界線
i=0;
while(str[i])
{
if(str[i] != ' ')
{
begin = i;
while(str[i] && str[i]!=' ') //it can't be while(str[i]!=' '), the last str si '\0' will be calculated
i++;
i=i-1;
end = i;
}
while(end>begin)
{
temp = str[begin];
str[begin]=str[end];
str[end]=temp;
end--;
begin++;
}
i++; //not i=i+2, to the last elem, it will be overload
}
printf("反轉結果string: %s\n",str);
getchar();
return 0;
}
參考文獻:http://www.cnblogs.com/rond/archive/2012/05/17/2505997.html