C语言实现移除字符串中的空格,并将空格数打印

某次被问到这一简单问题,想想以前学C语言的时候是知道的,那会却怎么也想不起来,现在回顾。


这里用两种方式实现移除:

  • 数组实现
#include <stdio.h>
#include <string.h>
/*用数组实现移除字符串中的空格,并将空格数打印*/
int main(void)
{
    char a[50] = "when the day nearby!";
    int i, j;
    int count = 0;
    for (i = 0, j = 0; a[i]; i++)
    {
        if (a[i] == ' '){
            count++;
        }else{
            a[j++] = a[i];
        }       
    }
    a[j] = '\0';

    printf("the changed string is: %s\n",a);
    printf("the blank number is: %d\n",count);
    getchar();
    return 0;
}
  • 指针实现
#include <stdio.h>
#include <malloc.h>
#include <string.h>

/*用C语言指针实现字符串中的空格的删除,并打印空格个数*/

void remove_str_blank(char *tempstr);

int main()
{
    char *str=(char *)malloc(100);
    printf("input the string: ");
    scanf("%[^\n]",str); //正则表达式格式化输入
    remove_str_blank(str);
    system("pause");
    return 0;
}

void remove_str_blank(char *tempstr)
{
    int count = 0;
    int len = strlen(tempstr);
    char *str2=(char *)malloc(sizeof(char)*len+1);
    char *str1 = tempstr;

    char *strx = str2;  //指向头节点

    while(*str1 != '\0'){
        if (*str1 == ' ')
        {
            count++;
        }else{
            *str2 = *str1;
            str2++;
        }
        str1++;
    }
    *str2 = '\0';   //加上末尾

    printf("the blank number is: %d\n",count);
    printf("the changed string is: %s\n",strx);

    free(strx);  //释放
}

类似的还有字符串的替换、删除、比较、添加等一系列字符串操作,可以参考c++标准库,里面提供了很多非常好用的函数,如:构造表示、容器、迭代器、字符访问等,以及string类的一些方法。

C/C++字符串函数


例程结果:
这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章