package com.fjf.test;
/**
* 替换空格
* @author fjf
*请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
* https://www.cnblogs.com/juncaoit/p/9000125.html (网友)
*
*/
public class Test02 {
public static void main(String[] args) {
String str = "We Are Happy";
str = Solution.replaceSpace1(new StringBuffer(str));
System.out.println(str);
str = Solution.replaceSpace2(new StringBuffer(str));
System.out.println(str);
}
static class Solution {
//String 的 replace方法
public static String replaceSpace1(StringBuffer str) {
String str2 = str.toString();
return str2.replaceAll(" ", "%20");
}
//Stringbuffer 开辟一个新的字符串来保存
public static String replaceSpace2(StringBuffer str) {
StringBuffer str2=new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)!=' '){
str2.append(str.charAt(i));
}else{
str2.append("%20");
}
}
return str2.toString();
}
}
}