该代码要完成倒置字符串的内容,单词依然是正确的任务
如:hello word!倒置为word! hello
思路是:1.先倒置字符串将hello word! 倒置为!drow olleh
2.再倒置每个单词,倒置为:word! hello
即可完成任务
代码展示:
#define _CRT_SECURE_NO_WARNINGS 1
//倒置字符串的内容,单词依然是正确的
//如:hello word倒置为word hello
//思路:先倒置字符串将hello word 倒置为drow olleh
//再倒置每个单词 倒置为:word hello
#include<stdio.h>
#include<string.h>
void Inversion(char*start,char*end) //倒置函数,如将hello word 倒置为drow olleh
{ //start和end分别表示字符串的起始地址和结束地址
while (start < end)
{
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
void invert_content(char*arr) //倒置内容,如:hello word倒置为word hello
{
int n=strlen(arr);
Inversion(arr, arr + n - 1); //倒置整个字符串
char* start = arr;
char* end = arr;
while (*(end - 1) != '\0')
{
while (*end != ' ' && *end != '\0')
{
end++;
}
Inversion(start, end - 1); //倒置单词
end++;
start = end;
}
}
int main()
{
char arr[100]={0};
gets_s(arr);
invert_content(arr); // 倒置内容
puts(arr);
return 0;
}
1.其中Inversion()函数完成倒置的作用,倒置字符串和倒置单词都可用该函数,该函数的思路是通过传入的字符串的首元素指针和尾元素指针,将首元素指针和尾元素指针指向的值进行交换,交换过后首元素指针向后移动,尾元素指针前移动。
2.invert_content()函数就是完成所给任务的函数
难点在于如何确定并遍历每个单词的首元素地址和尾元素地址
1.如图一开始start和end的位置初始化指向字符数组首元素
2.经过while循环,end的位置改变指向单词与单词之间的空格时停下
此时倒置单词hello便可通过Inversion(start, end - 1)
下一步将end向前移,start也移动到end的位置
便和一开始是一样的情况可开始循环
而循环完整个字符串要退出整个循环时end和start和end应处于如下的情况
此时start和end都指向’\0'的后面,所以进行while循环的条件应该是*(end - 1) != '\0'
实际运行的情况: