1. 程式人生 > >C語言實現移除字串中的空格,並將空格數列印

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類的一些方法。

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