CareerCup-1.5

Write a method to replace all spaces in a string with ‘%20’

简单题仍然无法做到无误。一定要摆脱对IDE和编译器的依赖!

#include <iostream>
using namespace std;

char* replaceSpace(char* str) {
    int count=0;
    char *p;
    for(p=str; *p!='\0'; p++)
    {
        if(*p==' ') count+=3;
        else count += 1;
    }
    char* ret = new char[count+1];
    char *q = ret;
    for(p=str; *p!='\0'; p++)
    {
        if(*p != ' ')
        {
            *q++ = *p;
        } else {
            *q++ = '%';
            *q++ = '2';
            *q++ = '0';
        }
    };
    *q=0;
    return ret;
}

int main()
{
    cout<<replaceSpace("abdd e  1 3 123 ");
    system("pause"); 
};

#include <iostream>
using namespace std;

char* replaceSpace(char* str) {
    int count=0;
    char *p;
    for(p=str; *p!='\0'; p++)
    {
        if(*p==' ') count+=3;
        else count += 1;
    }
    char* ret = new char[count+1];
    char *q = ret;
    for(p=str; *p!='\0'; p++)
    {
        if(*p != ' ')
        {
            *q++ = *p;
        } else {
            *q++ = '%';
            *q++ = '2';
            *q++ = '0';
        }
    };
    *q=0;
    return ret;
}

int main()
{
    cout<<replaceSpace("abdd e  1 3 123 ");
    system("pause"); 
};

Comments

comments powered by Disqus