题目描述 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 这个题较为简单
replace
直接实现def replaceSpace(s):
# return s.replace(" ","%20",s.count(" "))
return s.replace(' ','%20')
import re
def replaceSpace(self, s):
return re.sub(r' ', '%20', s)
public class Solution {
public String replaceSpace(StringBuffer str) {
return str.toString().replace(" ","%20");
}
}
package com.bigdataBC.JzOffer;
public class JzOffer2 {
public String replaceSpace(StringBuffer str) {
// return str.toString().replace(" ", "%20");
StringBuilder newsb=new StringBuilder();
for (int i=0;i<str.length();i++) {
char c=str.charAt(i);
if (c==' ') {
newsb.append("%20");
}else{
newsb.append(c);
}
}
return newsb.toString();
}
}