去除字符串中多餘的空格 C語言實現

比如“hello        world       hey     baby”

變成“hello world hey baby”


思想是設置兩個指針,前面的(front)一直往前走直到字符串結尾,後面的(last)複製front當前指向的字符,

當遇到多個空格時並不複製,而是等到front指向非空格字符時在往前走。


#include <stdio.h>

#include <stdlib.h>
#include <string.h>


void omitSpace(char *str){
char *front = str;
char *last = str;
if(str == NULL) return;
while((*front) == ' ') {++front;}            //omit space in the beginning
while((*front) != '\0'){
if((*front) == ' '){
*last = ' ';
while((*front) == ' '){
++front;
}
}else{
*last = *front;                 //can also add one if condition to avoid unnecessary assignment: if(last != front){*last = *front;}
++front;
}
++last;            //front has pointed to the next char, so don't ++front;
}
*last = '\0';
}


int main(){
char *cases[] = {"hello   world!!!", " hello world...", "  Hello  world???", "he   llo wor   ld   ...  "};
char **str;
int strIndex = 0;
int letterIndex = 0;
int casesNum = sizeof(cases) / sizeof(char*);                  //don't forget to be divided by sizeof(char*).
str = (char**)malloc(sizeof(cases));
for(strIndex = 0; strIndex < casesNum; ++strIndex){
str[strIndex] = (char*)malloc(1 + strlen(cases[strIndex]));
for (letterIndex = 0; letterIndex < strlen(cases[strIndex]); ++letterIndex)
{
str[strIndex][letterIndex] = cases[strIndex][letterIndex];
}
str[strIndex][letterIndex] = '\0';
}
for(strIndex = 0; strIndex < casesNum; ++strIndex){
printf("%s\n", str[strIndex]);
omitSpace(str[strIndex]);
printf("%s\n", str[strIndex]);
}
for(strIndex = 0; strIndex < casesNum; ++strIndex){
free(str[strIndex]);
}
free(str);
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章