题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
代码
public class Solution {
public String replaceSpace(StringBuffer str) {
int countSpace = 0;
for(int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if(c == ' ')
{
countSpace++;
}
}
int oldIndex = str.length() - 1;
int newIndex = oldIndex + 2 * countSpace;
str.setLength(newIndex + 1);
while(oldIndex < newIndex && oldIndex >= 0)
{
char c = str.charAt(oldIndex);
if(c == ' ')
{
str.setCharAt(newIndex--, '0');
str.setCharAt(newIndex--, '2');
str.setCharAt(newIndex--, '%');
}
else
{
str.setCharAt(newIndex--, c);
}
oldIndex--;
}
return str.toString();
}
}