如,
输入:I like coding!
输出:coding! like I
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <string.h>
void Reverse_arr(char* left, char* right)
{
assert(left);
assert(right);
char tem = 0;
while (left < right)
{
tem = *left;
*left = *right;
*right = tem;
left++;
right--;
}
}
int main()
{
char arr[101] = { 0 };
int len = 0;
char* left = NULL;
char* right = NULL;
//读取
gets(arr);
len = strlen(arr);
right = &arr[len - 1];
left = &arr[0];
//逆序整个句子
Reverse_arr(left, right);
//逆序每一个单词
while (*right != '\0')
{
right = left;
//right在正常情况下,遇到空格就可以判断单词结束,进行逆序单词操作了
//但还有一种特殊情况:单词在句子的末尾。
//此时right指向的不是空格,而是'\0'
//所以要把这2种情况都加上
while (*right != ' ' && *right != '\0')
{
right++;
}
//此时right指向空格,所以要自减1再传入逆序函数
Reverse_arr(left, right-1);
left = right + 1;
}
//输出
printf("%s\n", arr);
return 0;
}
标签:char,arr,right,单词,逆序,句子,left
From: https://blog.51cto.com/u_16509575/9399167