Sunday, 13 July 2014

Arrays and Strings : Write a method to replace all spaces in a string with ‘%20’.

#include <iostream>
#include <cstring>
#include <conio.h>

char* replace1(char *c){
    if(c == NULL) return NULL;
    int len = strlen(c);
    if(len == 0) return NULL;
    int cnt = 0;
    for(int i=0; i<len; ++i)
    {
        if(c[i] == ' ')
            ++cnt;
    }
    char *cc = new char[len+2*cnt+1];
    int p = 0;
    for(int i=0; i<len; ++i)
    {
        if(c[i] == ' ')
        {
            cc[p] = '%';
            cc[p+1] = '2';
            cc[p+2] = '0';
            p += 3;
        }
        else
        {
            cc[p] = c[i];
            ++p;
        }
    }
    cc[p] = '\0';
    return cc;
}
int main(){
    const int len = 100;
    char c[len] = "abcd efgh";
    cout<<replace1(c)<<endl;
    getch();
    return 0;
}

No comments:

Post a Comment