去除字符串中多余的空格 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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值