您的位置:首页 > 其它

CCI 1.4 将字符串空格替换成“%20”

2014-07-28 16:03 190 查看
编写一个方法,将字符串中的空格全部替换为“%20”。

package test;

public class ReplaceSpace {

public static char[] replace(char[] str){
if(str==null || str.length==0)
return str;
int count = 0;
for(char item : str)
if(item==' ')
count++;
int newLength = str.length + 2*count;
char[] newStr = new char[newLength];
for(int i=str.length-1; i>=0; i--){
if(str[i] == ' '){
newStr[newLength-1] = '0';
newStr[newLength-2] = '2';
newStr[newLength-3] = '%';
newLength -= 3;
}else{
newStr[newLength-1] = str[i];
newLength -= 1;
}
}
str = newStr;
return str;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
char[] case1 = null;
char[] case2 = new char[0];
char[] case3 = {'a', ' ', 'b'};
char[] case4 = {' ', ' ', ' '};

char[] result = replace(case3);
System.out.println(result);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字符串 数组
相关文章推荐