原文链接:谢谢作者
问题:将一句话里的单词进行倒置,标点符号不倒置。例如"i come from nanjing."输出结果为"nanjing. come from i"。
分析:第一步,将字符串完全倒置,即".gnijnan morf emoc i"
第二步,将每个单词进行部分倒置,即"nanjing. from come i"
倒置时设置begin和end两个指针分别指向字符串的开头和末尾。
#include <stdio.h>
#include <string.h>
void strReverse(char *str,int n)
{
int i = 0;
int j = 0;
int begin;
int end;
char temp;
//...............第一步:整体倒置......................//
j = n-1;
while (j>i)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
printf("after reversing wholly string = %s/n",str);
//...............第二步:按单词部分倒置......................//
i = 0;
while (str[i]!='/0')
{
if (str[i]!=' ')
{
begin = i;
while ((str[i]!='/0') && (str[i]!=' '))
{
i++;
}
i = i-1;
end = i;
}
while (begin<end)
{
temp = str[begin];
str[begin] = str[end];
str[end] = temp;
begin++;
end--;
}
i++;
}
}
int main()
{
char str[] = "i come from nanjing.";
int j = 0;
j = strlen(str);
printf(" string = %s/n",str);
strReverse(str,j);
printf(" string = %s/n",str);
return 0;
}