c语言字符串去掉空格制表符
在C语言中,字符串是由一系列字符构成的,其中可能包含了空格制表符等空白字符。如果想要去掉字符串中的空格和制表符,可以使用C语言提供的字符串处理函数和循环语句。
方法一:使用循环语句和条件判断去掉空格和制表符
首先,需要定义一个临时字符数组,用于存放去掉空格和制表符后的字符串。接着,可以使用while循环语句遍历原始字符串,同时使用条件判断去掉空格和制表符,并将处理后的字符存放到临时字符数组中。最后,再将临时字符数组赋值给原始字符串即可。
代码如下:
printf能输出空格吗```
#include <stdio.h>
#include <string.h>
void remove_spaces_and_tabs(char *str) {
    char temp[strlen(str)];
    int i, j = 0;
    for (i = 0; str[i] != '\0'; i++) {
        if (str[i] != ' ' && str[i] != '\t') {
            temp[j] = str[i];
            j++;
        }
    }
    temp[j] = '\0';
    strcpy(str, temp);
}
int main() {
    char s[100];
    printf("请输入字符串:");
    fgets(s, sizeof(s), stdin);
    remove_spaces_and_tabs(s);
    printf("去掉空格和制表符后的字符串为:%s\n", s);
    return 0;
}
```
方法二:使用C语言提供的字符串处理函数去掉空格和制表符
除了使用循环语句和条件判断去掉空格和制表符外,C语言还提供了一些字符串处理函数,如strtok、strspn、strcspn、isspace等可供使用。
其中,strtok函数可以将字符串按照指定的分隔符切割成若干个子串,可以使用空格和制表符作为分隔符来实现去掉空格和制表符的功能。具体实现如下:
```
#include <stdio.h>
#include <string.h>
void remove_spaces_and_tabs(char *str) {
    char *temp = strtok(str, " \t");
    int i = 0;
    while (temp != NULL) {
        str[i] = *temp;
        i++;
        temp = strtok(NULL, " \t");
    }
    str[i] = '\0';
}
int main() {
    char s[100];
    printf("请输入字符串:");
    fgets(s, sizeof(s), stdin);
    remove_spaces_and_tabs(s);
    printf("去掉空格和制表符后的字符串为:%s\n", s);
    return 0;
}
```
无论是方法一还是方法二,都可以实现去掉字符串中的空格和制表符的功能。使用哪种方法取决于个人喜好和实际情况。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。