About Me

My photo
Mostly software programming related blogs.

Friday, October 26, 2012

Replace blanks with a string in a given string


Problem - Given a string, replace all blanks with "%20"

C/C++ solution


#include <iostream>
#include <string.h>

using namespace std;

main(int argc, char* argv[]) {

        string input = "i am boy. You are Mrs Smith. ";

        int i  = 0;

        int len = input.size();

        cout << "input len before replace = " << len << endl;

        while (i < len) {
                if ( input[i] == ' ') {
                        input.replace(i, 1, "%20");
                        len = len + 2;
   
                }  

                i++;
        }  

        cout << "input = " << input << endl;

        cout << "input len after replace = " << input.size() << endl;
}

 ./a.out 
input len before replace = 29
input = i%20am%20boy.%20You%20are%20Mrs%20Smith.%20
input len after replace = 43

No comments: