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++字符串函數


例程結果:
這裏寫圖片描述

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