C语言 给字符串去空格
时间: 2023-12-24 09:04:22 浏览: 29
可以使用一个循环来遍历字符串中的每个字符,如果该字符是空格,则将其删除。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
void remove_spaces(char* str) {
int len = strlen(str);
int i, j;
for (i = 0, j = 0; i < len; i++) {
if (str[i] != ' ') {
str[j++] = str[i];
}
}
str[j] = '\0';
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, 100, stdin);
remove_spaces(str);
printf("After removing spaces: %s\n", str);
return 0;
}
```
在上面的代码中,`remove_spaces()` 函数接受一个字符串作为参数,并将其中的空格删除。主函数中使用 `fgets()` 函数从标准输入获取用户输入的字符串,并调用 `remove_spaces()` 函数来删除其中的空格。最后,输出修改后的字符串。
相关问题
c语言字符串去除空格
以下是C语言实现字符串去除空格的代码:
```c
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';
}
```
该函数的实现方法是遍历字符串中的每个字符,如果该字符不是空格,则将其复制到新的字符串中。最后,将新字符串的末尾设置为'\0',以表示字符串的结束。
需要注意的是,该函数只能去除字符串中的空格,而不能去除其他空白字符,如制表符、换行符等。
c语言 将字符串中空格删去
在C语言中,您可以使用`string.h`库中的函数`strcpy()`和`isspace()`来删除字符串中的空格。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void removeSpaces(char *str)
{
int i, j;
for (i = 0, j = 0; str[i]; i++)
if (!isspace(str[i]))
str[j++] = str[i];
str[j] = '\0';
}
int main()
{
char str[] = "This is a string with spaces";
printf("Original String: %s\n", str);
removeSpaces(str);
printf("String with spaces removed: %s\n", str);
return 0;
}
```
这将输出:
```
Original String: This is a string with spaces
String with spaces removed: Thisisastringwithspaces
```
请注意,`isspace()`函数用于检查给定字符是否为空格字符。如果字符为空格,则该函数返回非零值,否则返回零。