//写一个函数,将字符串翻转,翻转方式如下:“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