去掉字符串中多余的空格【微软面试提】

题目:

1、 remove掉给定字符串中的多余空格,要求达到以下要求
A 无连续相邻的两个空格
B 字符串开头和结尾无空格
C 新的一行开头和结尾无空格
  
要得到满分,必须满足以下两个条件
A 不能增加新的内存空间
B只能循环字符串一次
C不准用其他库函数

思路:循环过程中记录每个字符需要往前移动的距离,每个字符按照求出的距离向前移动(整个过程只需要遍历一次字符串数组)

我的实现代码如下:

/*This is the template of *.cpp files */
#include<iostream>
using namespace std;

void clear_space(char *p){
    int jump = 0;
    int i = 0;
    int temp = 0;
    while(p[i] == ' ' && p[i] != '\0'){
        ++jump;
        ++i;
    }
    while(p[i] != '\0'){
        if(p[i] != ' '){
            p[i - jump] = p[i];
            temp = 0;
        }else{
            ++temp;
            if(temp > 1)
                ++jump;
            else
                p[i - jump] = p[i];
        }
        ++i;
    }
    if(p[i - 1] == ' '){
        p[i - jump - 1] = ' ';
    }
    p[i - jump] = '\0';
}

int main(){
    char q[] = "    kjf     dshgjk  sjdhfdj asdf   sdf  dsf ";
    int i = 0;
    cout<<q<<endl;
    clear_space(q);
    cout<<q<<endl;
    return 0;
}

posted on 2014-03-12 10:40  程序猿猿猿  阅读(472)  评论(0编辑  收藏  举报

导航