577 反转字符串中的单词 c语言
时间: 2024-05-16 16:19:18 浏览: 94
字符串逆序-使用C语言实现的字符串按单词逆序.zip
您好!要在 C 语言中反转字符串中的单词,可以使用以下代码:
```c
#include <stdio.h>
#include <string.h>
void reverseWords(char* str) {
int i, j;
int start = 0;
int end = 0;
int length = strlen(str);
// 反转整个字符串
for (i = 0, j = length - 1; i < j; i++, j--) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
// 反转每个单词
for (i = 0; i <= length; i++) {
if (str[i] == ' ' || str[i] == '\0') {
end = i - 1;
// 反转单词
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
start = i + 1;
}
}
}
int main() {
char sentence[] = "Hello world! Welcome to C programming.";
printf("Original sentence: %s\n", sentence);
reverseWords(sentence);
printf("Reversed words: %s\n", sentence);
return 0;
}
```
此代码将输出:
```
Original sentence: Hello world! Welcome to C programming.
Reversed words: olleH dlrow! emocleW ot C .gnimmargorp
```
希望能帮到您!如果有任何其他问题,请随时提问。
阅读全文