c语言实现 字符串反序 并 清除多余空格
时间: 2023-09-04 18:09:01 浏览: 74
以下是使用C语言实现字符串反序并清除多余空格的示例代码:
```c
#include <stdio.h>
#include <string.h>
void reverseString(char *str) {
int left = 0;
int right = strlen(str) - 1;
// 反序字符串
while (left < right) {
char temp = str[left];
str[left] = str[right];
str[right] = temp;
left++;
right--;
}
}
void removeExtraSpaces(char *str) {
int n = strlen(str);
// 从左到右遍历,删除多余的空格
int i, j;
for (i = 0, j = 0; i < n && str[i] != '\0'; i++) {
if (str[i] != ' ' || (i > 0 && str[i-1] != ' ')) {
str[j] = str[i];
j++;
}
}
// 添加字符串结束符
str[j] = '\0';
}
int main() {
char str[100];
printf("请输入一个字符串:");
fgets(str, sizeof(str), stdin);
// 去除换行符
if (str[strlen(str) - 1] == '\n') {
str[strlen(str) - 1] = '\0';
}
// 反序字符串
reverseString(str);
// 清除多余空格
removeExtraSpaces(str);
// 输出结果
printf("反序并清除多余空格后的字符串为:%s\n", str);
return 0;
}
```
这段代码首先定义了两个函数:`reverseString()` 和 `removeExtraSpaces()`。`reverseString()` 函数用于反序字符串,使用双指针法将字符串首尾字符进行交换。`removeExtraSpaces()` 函数用于清除多余的空格,遍历字符串并删除连续的多个空格,只保留一个空格。
在 `main()` 函数中,首先使用 `fgets()` 函数从标准输入获取一个字符串,并去除末尾的换行符。然后调用 `reverseString()` 函数反序字符串,再调用 `removeExtraSpaces()` 函数清除多余的空格。最后,输出处理后的结果。
请注意,这段代码假设输入的字符串长度不会超过100个字符。如果需要处理更长的字符串,可以适当修改代码中的数组大小。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)