标签:
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
public class Solution02 {
public String replaceSpace(StringBuffer str) {
int oldLength = str.length();
int numOfSpace = 0;
for (int i = 0; i < oldLength; i++) {
if (str.charAt(i) == ‘ ‘) {
numOfSpace++;
}
}
int newLength = oldLength + numOfSpace * 2;
int left = oldLength - 1;
int right = newLength - 1;
for (int n = 0; n < numOfSpace * 2; n++){
str.append(‘ ‘);
}
while (left >= 0 && right > left) {
if (str.charAt(left) == ‘ ‘) {
str.setCharAt(right--, ‘0‘);
str.setCharAt(right--, ‘2‘);
str.setCharAt(right--, ‘%‘);
left--;
} else {
str.setCharAt(right--, str.charAt(left--));
}
}
return str.toString();
}
public static void main(String[] args) {
StringBuffer test = new StringBuffer("hello world ");
Solution02 solution = new Solution02();
System.out.println(solution.replaceSpace(test));
}
}
新人水平有限,请大家多多指教!
标签:
原文地址:http://www.cnblogs.com/rosending/p/5603668.html