topic
Please implement a function to replace each space in a string with "% 20". For example, when the string is We Are Happy. The string after replacement is We% 20Are% 20Happy.
Code implementation 1
public class Solution {
public String replaceSpace(StringBuffer str) {
return str.toString().replace(" ", "%20");
}
}
Code implementation 2
public class Solution {
public String replaceSpace(StringBuffer str) {
StringBuffer result = new StringBuffer();
String target = str.toString();
for(int i = 0; i < target.length(); i++){
char c = target.charAt(i);
if(c == ' '){
result.append("%20");
}else{
result.append(c);
}
}
return result.toString();
}
}