字符串替换
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy Coder.则经过替换之后的字符串为We%20Are%20Happy%20Coder
public class ReplaceSpace {
public static void main(String[] args) {
String str = "We Are Happy Coder.";
System.out.println(replaceSpace(str, " ", "%20"));
System.out.println(replaceSpace2(str));
}
/**
* 调用api实现内容替换
*
* @param str
* @return
*/
private static String replaceSpace2(String str) {
return str.replaceAll("\\s", "%20");
}
/**
* 替换内容
*
* @param str 原始的句子
* @param replaceStr 被替换的内容
* @param replacement 替换的内容
* @return
*/
private static String replaceSpace(String str, String replaceStr, String replacement) {
int length = str.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
char b = str.charAt(i);
if (String.valueOf(b).equals(replaceStr)) {
sb.append(replacement);
} else {
sb.append(b);
}
}
return sb.toString();
}
}