剑指Offer面试题2:替换空格

如书中介绍实现

#include<iostream>
using namespace std;
void replaceblank(char sentence[],int length,int orilen, int blalen)
{
    if (sentence == NULL || length <= 0)
        return;
    int p1=orilen;
    int p2=orilen+2*blalen;
    if(p2>length)
        return;
    while (p1!=p2)
    {
        if(sentence[p1]!=' ')
            sentence[p2--]=sentence[p1--];
        else{
            sentence[p2--]='0';
            sentence[p2--]='2';
            sentence[p2--]='%';
            --p1;
        }

    }

}
int main(){
    char sentence[100] = "We Are Happy.";
    int orilength = 0;
    int blalength = 0;

    while(sentence[orilength]!='\0')
    {
        if(sentence[orilength]==' ')
            ++blalength;
        ++orilength;
    }
    cout<<sentence<<endl;
    replaceblank(sentence,sizeof(sentence),orilength,blalength);
    cout<<sentence<<endl;
}


你可能感兴趣的:(面试题,剑指offer)