c语言中,去除字符串中的空格
时间: 2023-12-11 22:05:42 浏览: 222
在 C 语言中,可以使用以下方法去除字符串中的空格:
1. 使用循环遍历字符串,逐个字符判断是否为空格。
2. 如果遇到空格,则后面的字符依次向前移动一个位置,覆盖空格。
3. 最后将字符串的长度减去空格的个数,将末尾多余的字符设置为字符串结束符号 '\0'。
下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
void removeSpaces(char* str) {
int len = strlen(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[] = "C 语言中,去除 字符串 中的 空格";
printf("原始字符串:%s\n", str);
removeSpaces(str);
printf("去除空格后的字符串:%s\n", str);
return 0;
}
```
运行结果:
```
原始字符串:C 语言中,去除 字符串 中的 空格
去除空格后的字符串:C语言中,去除字符串中的空格
```
通过以上方法,可以实现在 C 语言中去除字符串中的空格。
相关问题
C语言中去除字符串中空格
可以使用C语言中的字符串处理函数`strcpy`和`isspace`来去除字符串中的空格。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void remove_spaces(char *str) {
char *temp = str;
while (*str) {
if (!isspace((unsigned char)*str))
*temp++ = *str;
str++;
}
*temp = '\0';
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin);
remove_spaces(str);
printf("String after removing spaces: %s\n", str);
return 0;
}
```
在上面的代码中,`remove_spaces`函数接收一个指向字符串的指针,并将字符串中的空格移除。然后,我们在`main`函数中读取用户输入的字符串,调用`remove_spaces`函数,并将移除空格后的字符串打印输出。
C语言怎么把字符串中空格去除
可以使用C语言中的字符串处理函数 `strcpy()` 和 `strcat()` 来去除字符串中的空格。具体操作如下:
1. 遍历字符串,将空格替换为 '\0'。
2. 将非空格字符拷贝到新的字符串中。
以下是示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
void removeSpaces(char* str) {
int i, j;
for (i = 0, j = 0; str[i] != '\0'; i++) {
if (str[i] != ' ') {
str[j++] = str[i];
}
}
str[j] = '\0';
}
int main() {
char str[MAX_LEN];
printf("请输入带有空格的字符串:");
fgets(str, MAX_LEN, stdin);
removeSpaces(str);
printf("去除空格后的字符串为:%s\n", str);
return 0;
}
```
输入示例:
```
请输入带有空格的字符串:hello world
```
输出示例:
```
去除空格后的字符串为:helloworld
```