面试题05. 替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = “We are happy.”
输出:“We%20are%20happy.”
解题代码
import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @Auther: truedei * @Date: 2020 /20-5-6 22:46 * @Description: */ public class TestA { static public String replaceSpace(String s) { //1693648纳秒 return s.replaceAll("[ ]", "%20"); //1355205纳秒 return s.replace(" ","%20"); //636976纳秒 StringBuilder s1 = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if(s.charAt(i)==(char)' '){ s1.append("%20"); }else { s1.append(s.charAt(i)); } } return s1.toString(); //594273纳秒 String s1=""; for (int i = 0; i < s.length(); i++) { if(s.charAt(i)==(char)' '){ s1=s1+"%20"; }else { s1=s1+s.charAt(i); } } return s1; } }