翻转句子中单词的顺序

时间:2023-01-08 11:43:27
题目:输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。
句子中单词以空格隔开,为简单起见,标点符号和普通字母一样处理。

例如:输入"I am a student.",则输出:"student. a am I"。

#include <stdio.h>
#include <string.h>
#include <malloc.h>

char *reverse_sentense(char *s) {
int n = 0;
int locates[strlen(s) + 1];//记录单词始末位置
char *tmp = malloc(sizeof(char) * strlen(s));
char *cur = s;
while (*cur != '\0') {
//若遇到空格,记录新单词的结束位置
for (; ' ' == *cur && *cur!='\0'; cur++);//跳过空格
locates[n++] = cur - s;//单词开始位置
for (; ' ' != *cur && *cur!='\0'; cur++);//找到下一个空格
locates[n++] = cur - s - 1;//单词末尾位置
}
n--;
while (n > 0) {
strncat(tmp, s + locates[n - 1], locates[n] - locates[n - 1] + 1);
if (n > 1) {
strcat(tmp, " ");//中间的单词用空格分开
}
n -= 2;
}
strcpy(s, tmp);
free(tmp);
return s;
}

int main() {
//char *s = " I am a student.";//字符串常量不能修改
char *s = malloc(sizeof(char) * 100);
strcpy(s, " I am a student.");
reverse_sentense(s);
printf("%s\n", s);
free(s);
s = NULL;
return 0;
}

//给自己的警告:字符串常量是只读的,绝对不要对字符串常量进行任何更改操作。