#include<stdio.h>
#include<string.h>
#include<assert.h>
void reverse(char* left,char* right)//用来逆序字符串中的数据
{
assert(left);
assert(right);
while (left < right)
{
char t = *left;
*left = *right;
*right = t;
left++;
right--;
}
}
int main()
{
char a[101] = { 0 };
gets(a);
int len = strlen(a);
//逆序整个字符串
reverse(a,a+len-1);
//逆序每个单词
char* start = a;
while (*start != '\0')//当*start=‘\0’时,就说明已经没有单词了
{
char* end = start;
while (*end!=' '&&*end!='\0')//因为输入的时候,每个单词之间用空格隔开
{
end++;
}
reverse(start, end - 1);//因为这时候的end指向空格,end-1是单词的尾地址(一个单词最后一个字母的地址)
//end-1是一个单词的右边界,start是左边界
if (*end != '\0')
{
end++;
}
start = end;//将下一个单词的首地址赋给start
}
printf("%s\n", a);
return 0;
}
//假设输入 I like beijing
//输出结果为 beijing like I
//
逆置字符串
最新推荐文章于 2024-08-09 17:46:50 发布