删除字符串中所有空格 用c语言写出代码
时间: 2024-06-17 15:02:53 浏览: 20
在C语言中,可以使用循环遍历字符串的每个字符,判断是否为空格,如果不是空格则将其保留,最后将保留的字符重新组成一个新的字符串。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
void removeSpaces(char* str) {
int count = 0;
for (int i = 0; str[i]; i++) {
if (str[i] != ' ') {
str[count++] = str[i];
}
}
str[count] = '\0';
}
int main() {
char str[100];
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // 去除fgets函数读取的换行符
removeSpaces(str);
printf("删除空格后的字符串为:%s\n", str);
return 0;
}
```
这段代码中,`removeSpaces`函数用于删除字符串中的空格。在`main`函数中,首先使用`fgets`函数获取用户输入的字符串,并使用`strcspn`函数去除输入字符串末尾的换行符。然后调用`removeSpaces`函数删除字符串中的空格,并输出删除空格后的字符串。
相关问题
用c语言写出统计一个字符串中的字母,数字、空格和其他字符的个数
你好,这个问题可以回答。以下是用 C 语言实现统计字符串中字母、数字、空格和其他字符个数的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一个字符串:");
fgets(str, 100, stdin);
for (int i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isdigit(str[i])) {
digits++;
} else if (isspace(str[i])) {
spaces++;
} else {
others++;
}
}
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
希望能对你有所帮助。
输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数用c语言写出代码
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
int i, letters = 0, digits = 0, spaces = 0, others = 0;
printf("请输入一行字符:\n");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
if (isalpha(str[i])) {
letters++;
} else if (isdigit(str[i])) {
digits++;
} else if (isspace(str[i])) {
spaces++;
} else {
others++;
}
}
printf("字母个数:%d\n", letters);
printf("数字个数:%d\n", digits);
printf("空格个数:%d\n", spaces);
printf("其他字符个数:%d\n", others);
return 0;
}
```
--相关问题--:
1. 如何统计中文字符的个数?
2. 如何统计输入的字符串