题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
算法实现:
法一:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.nextLine();
String[] sc = str.split(" ");
String result = "";
for(int i = 0; i < sc.length - 1;i++){
result += sc[i] + "%20";
}
result = result + sc[sc.length - 1];
System.out.println(result);
}
}
}
法二:
import java.util.Scanner;
public class Main {
public String replaceSpace(String str) {
return str.toString().replaceAll("\\s", "%20");
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.nextLine();
Main ti = new Main ();
System.out.println(ti.replaceSpace(str));
}
}
}