倒序输出字符串中的单词
【问 题】 将一个字符数组中的单词顺序反转,要求不借助其它字符数组或者指针链表,保存反转后的字符数组,单词间以空格分隔。
【思 路】 先将字符数组全部反转,“This is a test”–> “tset a si sihT”, 再将单词逐个反转,最后得到要求的数组。
先把一个字符串全部翻转,再逐个反转单词。其实我觉得还有更好的方法,完全可以省掉空间和时间上的浪费,一遍扫过就可以了。代码如下:
#include <stdio.h>
int main(int argc, char *argv[])
{
char str[] ="This is a test";
int len = sizeof(str);
char * p1, * p2, * p3;
p1 = str + len - 2;
while(p1 != str)
{
p3 = p1; //remember start position
// find the space char
while(*p1 != ' ' && p1 != str)
{
p1--;
}
// output a section
p2 = (p1 == str ? p1 : p1+1);
for (;p2!=p3;p2++)
printf("%c", *p2);
printf("%c", *p3);
// output the space char
if (p1==str)
break;
p1--;
printf(" ");
}
return 0;
}