设计需求
有一个以空格为分隔符的字符串"this is a book",
以单词为单元将其逆置,变为"book a is this" (不允许定义新数组)
程序实现
#include <stdio.h>
#include <string.h>
void StrReverse(char *str1, int len)
{
char *str2 = NULL;
if(str1 == NULL || len <= 0){
return;
}
str2 = str1+len-1;
len /= 2;
while(len--)
{
*str1 = *str1 ^ *str2;
*str2 = *str1 ^ *str2;
*str1 = *str1 ^ *str2;
str1++;
str2--;
}
}
void StrWordReverse(char *str)
{
int strlens;
char *pHead = str;
char *pEnd = str;
if(str == NULL){
return;;
}
strlens = strlen(str);
StrReverse(pHead, strlens);
while(*pHead)
{
do{
pEnd++;
}while((*pEnd != ' ') && (*pEnd != '\0'));
StrReverse(pHead, pEnd-pHead);
pHead = ++pEnd;
}
}
int main(int argc, const char *argv[])
{
char str[100] = "this is a book";
printf("Before:%s\n", str);
StrWordReverse(str);
printf("After :%s\n", str);
return 0;
}
打印测试:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200306090043142.png)