#include <stdio.h>
#include <ctype.h>
#include <string.h>
void reverse_word(char *start, char *end) {
while (start < end) {
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
void reverse_words(char *str) {
char *word_start = str;
while (*str) {
if (isspace(*str)) {
if (word_start != str) {
reverse_word(word_start, str - 1);
}
while (isspace(*str)) {
str++;
}
word_start = str;
} else {
str++;
}
}
if (word_start != str) {
reverse_word(word_start, str - 1);
}
// 去除开头和结尾的空格
while (isspace(*word_start)) {
word_start++;
}
char *new_end = word_start + strlen(word_start) - 1;
while (new_end > word_start && isspace(*new_end)) {
new_end--;
}
*(new_end + 1) = '\0';
strcpy(str, word_start);
}
int main() {
char str[1000];
printf("请输入字符串: ");
fgets(str, sizeof(str), stdin);
// 去除fgets读取的换行符
str[strcspn(str, "\n")] = '\0';
reverse_words(str);
printf("处理后的字符串: %s\n", str);
return 0;
}