    #include <algorithm>
    #include <string>
    #include <iostream>
    #include <cctype>
    #include <functional>
    
    using namespace std;

    // A function object that will take a character, and append either "%20" or the 
    // original character to our new string    
    struct Converter
    {
    	std::string* pS;  // this points to our string we will build
    
    	Converter(std::string* s) : pS(s) {}
    
    	void operator()(char ch) 
    	{
    		if ( isspace(ch) )
    			(*pS) += "%20";   // it's a space, so replace
    		else
    			*pS += ch;    // it is not a space, so use the same character
    	}
    };
    
    // trim spaces from end of string
    std::string &rtrim(std::string &s) 
    {
    	s.erase(std::find_if(s.rbegin(), s.rend(), 
                std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
    	return s;
    }

    // function to return the new string by looping over the original string 
    string getNewString(const std::string& s)
    {
    	std::string outStr;  // our new string

        // loop over each character, calling our Coverter::operator()(char) function
    	for_each(s.begin(), s.end(), Converter(&outStr));
    	return outStr;
    }
    
    int main()
    {
    	string instring = "This string has spaces ";
        cout << getNewString(rtrim(instring));
    }
