Problem
Write a method to replace all spaces in a string with ‘%20’. You may assume that the string has sufficient space at the end to hold the additional characters,and that you are given the “true” length of the string. (Note: If implementing in Java,please use a character array so that you can perform this operation in place.)
Example1
Input: "Mr John Smith ", 13
Output: “Mr%20John%20Smith”
Example2
Input: " ", 5
Output: “%20%20%20%20%20”
Solution
class Solution {
public:
string replaceSpaces(string S, int length) {
string ret = "";
if(length == 0)
return ret;
for(int i = 0;i<length;++i)
{
if(S[i] == ' ')
{
ret += "%20";
}
else
{
ret += S[i];
}
}
return ret;
}
};