题目:
实现一个函数,把字符串中的每个空格替换成“%20”。
例如:输入“We are happy”,则输出“We%20are%20happy”。
分析一:
使用stringbuilder,遍历原字符串,往stringbuilder对象中追加,碰到空格,追加%20。
代码一:
package offer.xzs.four;
public class ReplaceSpace02 {
public static void main(String[] args) {
String str = " We are happy ";
String s = replaceStr(str);
System.out.println(s);
}
public static String replaceStr(String str) {
if (str == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (String.valueOf(str.charAt(i)).equals(" ")) {
sb.append("%20");
} else {
sb.append(String.valueOf(str.charAt(i)));
}
}
return sb.toString();
}
}
分析二:
先遍历一遍,得到空格的数量,每一个空格在字符串后面追加两倍的字符空间,设置两个指针,一个指向原字符串的末尾,一个指向现在字符串的末尾,从后往前遍历。
代码二:
package offer.xzs.four;
public class ReplaceSpace03 {
public static void main(String[] args) {
String str = " We are happy ";
String s = replaceStr(str);
System.out.println(s);
}
public static String replaceStr(String str) {
if (str == null) {
return null;
}
int index1 = str.length() - 1;
for (int i = 0; i <= index1; i++) {
if (String.valueOf(str.charAt(i)).equals(" ")) {
str += " ";
}
}
int index2 = str.length() - 1;
char[] chars = str.toCharArray();
while (index1 >= 0 && index2 > index1) {
char c = chars[index1--];
if (c == ' ') {
chars[index2--] = '0';
chars[index2--] = '2';
chars[index2--] = '%';
} else {
chars[index2--] = c;
}
}
String result = new String(chars);
return result;
}
public static String replaceStr1(String str) {
str.replace(" ", "%20");
return str;
}
}