原文:
Write a method to replace all spaces in a string with ‘%20’.
译文:
写一个函数,把字符串中所有的空格替换为%20 。
package chapter_1_arraysandstring;
import java.util.Scanner;
/**
* 写一个函数,把字符串中所有的空格替换为%20
*
* @author LiangGe
*
*/
public class Question_1_5 {
/**
* 通过StringBuffer拼接结果,遍历替换
*/
public static String spaceReplace(String str) {
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();
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String str = scanner.nextLine();
str = spaceReplace(str);
System.out.println(str);
}
}
}