用c语言给我写出将一句话的单词进行倒置,标点不倒置的代码
时间: 2024-01-22 09:18:51 浏览: 27
下面是一个简单的 C 语言程序,能够将输入的句子中的单词进行倒置,但标点不会倒置:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
void reverse(char *start, char *end) {
char temp;
while (start < end) {
temp = *start;
*start++ = *end;
*end-- = temp;
}
}
void reverse_words(char *str) {
char *word_start = NULL;
char *temp = str;
// 倒置整个句子
reverse(str, str + strlen(str) - 1);
// 倒置每个单词
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++;
}
}
int main() {
char str[MAX_LEN];
printf("请输入一句话:\n");
fgets(str, MAX_LEN, stdin);
reverse_words(str);
printf("倒置后的结果为:%s", str);
return 0;
}
```
该程序使用了两个函数,`reverse` 用于倒置字符串,`reverse_words` 用于倒置句子中的每个单词,然后在 `main` 函数中调用 `reverse_words` 函数对输入的句子进行处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)