题目描述:
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
题目解答:
import java.util.*;
import java.math.*;
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
System.out.println("Solution1:");
System.out.println(replaceSpace1(new StringBuffer(str)));
System.out.println("Solution2:");
System.out.println(replaceSpace2(new StringBuffer(str)));
input.close();
}
//Solution1:通过调用 String 的 replaceAll(str, newstr) 方法
public static String replaceSpace1(StringBuffer str) {
return new String(str).replaceAll(" ", "%20");
}
//Solution2:通过遍历字符串找到空格并替换
public static String replaceSpace2(StringBuffer str) {
if (str == null) {
return null;
}
StringBuffer result = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
result.append("%20");
} else {
result.append(str.charAt(i));
}
}
return result.toString();
}
}
运行结果:
Input:
We Are Happy
Output:
Solution1:
We%20Are%20Happy
Solution2:
We%20Are%20Happy