c语言将一句话的单词进行倒置
时间: 2024-02-05 12:12:37 浏览: 83
以下是用 C 语言实现将一句话的单词进行倒置的代码:
```c
#include <stdio.h>
#include <string.h>
void reverse(char* start, char* end) {
char temp;
while (start < end) {
temp = *start;
*start++ = *end;
*end-- = temp;
}
}
void reverseWords(char* str) {
char* word_start = NULL;
char* temp = str;
while (*temp) {
if (word_start == NULL && *temp != ' ') {
word_start = temp;
}
if (word_start && (*(temp + 1) == ' ' || *(temp + 1) == '\0')) {
reverse(word_start, temp);
word_start = NULL;
}
temp++;
}
reverse(str, temp - 1);
}
int main() {
char str[100];
printf("Enter a sentence: ");
fgets(str, 100, stdin);
printf("Original sentence: %s", str);
reverseWords(str);
printf("Reversed sentence: %s", str);
return 0;
}
```
输入一个句子后,程序会将句子中每个单词的顺序进行倒置,输出结果为倒置后的句子。
阅读全文