c语言删除字符串空格指针
时间: 2023-12-12 09:02:42 浏览: 37
下面是一个简单的 C 代码示例,用于删除字符串中的空格:
```c
#include <stdio.h>
#include <string.h>
void remove_spaces(char* str) {
int i, j;
for (i = 0, j = 0; str[i]; i++) {
if (str[i] != ' ') {
str[j++] = str[i];
}
}
str[j] = '\0';
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // 从标准输入读取字符串
remove_spaces(str);
printf("String after removing spaces: %s\n", str);
return 0;
}
```
在这个例子中,`remove_spaces`函数通过遍历字符串来删除空格。当遇到非空格字符时,将其复制到字符串的新位置,然后将新位置指向下一个字符。最后,将新位置指向的字符设置为 `'\0'`,以表示新字符串的结尾。在 `main`函数中,我们使用`fgets`函数从标准输入读取字符串,并调用`remove_spaces`函数来删除空格。
相关问题
c语言统计字符串空格多少个
很高兴回答你的问题!对于统计字符串中空格的数量,在C语言中我们可以使用循环逐个字符比对的方法,以下是一个简单的代码示例:
```c
#include <stdio.h>
#include <string.h>
int count_spaces(char* str) {
int count = 0;
for (int i = 0; i < strlen(str); i++) {
if (str[i] == ' ') {
count++;
}
}
return count;
}
int main() {
char str[] = "Hello world, how are you?";
int spaces = count_spaces(str);
printf("Number of spaces in string: %d", spaces);
return 0;
}
```
以上代码中,我们首先定义了一个函数 `count_spaces` ,它的输入是一个字符指针 `str` ,输出是整型变量 `count` ,代表字符串中空格的数量。在函数中,我们使用了一个循环逐个比对字符串中的字符,如果某个字符是空格,我们将计数器 `count` 的值加一。最后,在 `main` 函数中,我们定义了一个测试用的字符串 `str` ,并调用了 `count_spaces` 函数,将空格的数量存放在变量 `spaces` 中并输出。
C语言删除字符串中的空格
可以使用C语言的字符串处理函数来删除字符串中的空格。以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.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("请输入一个带有空格的字符串:\n");
fgets(str, 100, stdin);
remove_spaces(str);
printf("删除空格后的字符串为:%s\n", str);
return 0;
}
```
这个程序中,`remove_spaces` 函数接收一个字符串指针参数,然后遍历字符串中的每个字符,如果字符不是空格,就将它复制到一个新的位置,最后在字符串末尾添加一个空字符 '\0'。主函数调用 `remove_spaces` 函数来删除输入字符串中的空格,并输出结果。