java实现替换空格,谁能优化一下我的代码?
请实现一个函数,把字符串中的每个空格替换成%20。例如输入“We are happy.”,则输出“We%20are%20happy.”。
实现我已经写出来了,谁有什么相应的优化方案么?要求用java
public class ReplaceSpace
{
public StringBuffer replace(StringBuffer str)
{
if (null == str)
{
System.out.println("字符串为空!");
return null;
}
for (int i=0; i<str.length(); i++)
{
char index = str.charAt(i);
if (index == ' ')
{
str.replace(i, i+1, "%20");
}
}
return str;
}
}
public class ReplaceSpaceTest
{
public static void main(String[] args)
{
ReplaceSpace replacespace = new ReplaceSpace();
StringBuffer str = new StringBuffer("We are happy");
//str = null;
replacespace.replace(str);
System.out.println(str);
}
}
public StringBuffer replace(StringBuffer str) {
if (null == str) {
System.out.println("字符串为空!");
return null;
}
int n = str.length();
int i = 0;
char index = 0;
while (i < n) {
index = str.charAt(i);
if (index == ' ') {
str.replace(i, i + 1, "%20");
i +=3;//第次把' '变成"%20"后会增加2个字符
} else {
i++;
}
}
return str;
}