请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
package timufuxi;
public class kaoshi2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer sb=new StringBuffer("absdefg ");
System.out.println(sb);
Solution solution=new Solution();
String temp=solution.replaceSpace(sb);
System.out.println(temp);
}
}
class Solution{
public String replaceSpace(StringBuffer str) {
int index=0;
int length=" ".length();//被替换的字符串的长度,
String name="%20";//要添加的字符串
while(str.indexOf(" ",index)>=index)//“ ”表示要搜索的空格,第一个index是搜索开始的地方
{
index=str.indexOf(" ");//持续的进行搜索
str.replace(index, index+length, name);//当字符串中没有空格时,str.indexOf(" ")的值是-1
}
return str.toString();//从StringBuffer到String: String str = sb.toString();
}
}