面试题【1】_删除字符串中多余的空格

原文网址:http://www.cnblogs.com/xia520pi/archive/2012/06/28/2568708.html

 

1、题目

  给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。

  比如 :

 

" I like http://hi.baidu.com/mianshiti " à "I like http://hi.baidu.com/mianshiti"。

 

2、代码

 

#include<stdio.h>

#include<string.h>

 

void removeExtraPalce(char * str);

 

main(){

    char * str = " I like http://hi.baidu.com/mianshiti ";

    removeExtraPalce(str);

    return 0;

}

 

void removeExtraPalce(char * str)

{

    int i,count=0;

    int length =strlen(str);

    bool begin;

 

    if(str[0] != ' '){

        begin=true;

    }else{

        begin=false;

    }

 

    printf("[");

    for(i=0;i<length;i++){

        //去掉字符串头部空格

        if(str[i]==' ' && !begin){

            if(i<length-1 && str[i+1] !=' '){

                begin=true;

            }

            continue;

        }

 

        if(begin){

            if(str[i] == ' '){

                if(i<length-1 && str[i+1] !=' '){

                    //只输出中间的一个空格

                    printf("%c",str[i]);

                    count=0;

                }

                count++;

                continue;

            }

        }

 

        printf("%c",str[i]);

    }

 

    printf("]\n");

}

 

3、结果

3.1 测试1

  字符串:"I like http://hi.baidu.com/mianshiti"

  运行结果:

    

3.2 测试2

  字符串:"   I like http://hi.baidu.com/mianshiti"

  运行结果:

    

3.3 测试3

  字符串:"   I   like http://hi.baidu.com/mianshiti"

  运行结果:

    

3.4 测试4

  字符串:"   I   like   http://hi.baidu.com/mianshiti"

  运行结果:

    

3.5 测试5

  字符串:"   I   like   http://hi.baidu.com/mianshiti   "

  运行结果:

    

posted @ 2015-12-08 10:54  Kconfig  阅读(357)  评论(0)    收藏  举报