牛客網----將一個字串中的空格替換成“20% ”。
阿新 • • 發佈:2019-02-01
方法一:
public class Demo7 { public static void main(String[] args) { StringBuffer str = new StringBuffer(); str.append("We are family"); System.out.println(replaceSpace(str)); } public static String replaceSpace(StringBuffer str) { String str1=str.toString(); String str2 = str1.replace(" ", "%20"); return str2; } }
方法二:
public class Demo8 { public static void main(String[] args) { System.out.println(replaceSpace(new StringBuffer("We are family"))); } public static String replaceSpace(StringBuffer str) { String str1=str.toString(); char[] ch = str1.toCharArray(); StringBuilder sBuilder = new StringBuilder(); for (char c : ch) { if (c==' ') { sBuilder.append("%20"); }else { sBuilder.append(c); } } String str2 = sBuilder.toString(); return str2; } }