您的位置:首页 > 其它

实现一个函数,将字符串中的空格替换成"%20"

2016-10-10 11:14 387 查看
请实现一个函数,将字符串中的每个空格替换成"%20",例如输入"We are happy.",则输出"We%20are%20happy."

我的程序时间复杂度可以达到O(n),但是需要开辟一个新的字符串数组。

public  class test {
public static void main(String[] args) {
String str = "We are happy.";
char[] ch = str.toCharArray();
int len = ch.length;
char[] ch1 = ReplaceBlank(ch, len);
System.out.print(ch1);
}
public static char[] ReplaceBlank(char[] str, int len){
if(len<=0)
return null;
int count = 0;
for(int i=0;i<len;i++){
if(str[i]==' ')
++count;		//计数原字符串中的空格数目
}
int newLength = len + count*2;
char[] newStr = new char[newLength];  //替换后的字符串数组的大小
if(newLength == len)
return null;
int oldIndex = len-1;
int newIndex = newLength-1;
while(oldIndex>=0){
if(str[oldIndex]==' '){
newStr[newIndex--]='0';
newStr[newIndex--]='2';
newStr[newIndex--]='%';
}else{
newStr[newIndex--] = str[oldIndex];
}
oldIndex--;
}
return newStr;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐