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);
}
}
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);
}
}
相关文章推荐
- 《CTCI》1.4 替换字符串中的空格为“%20”
- 剑指offer 1,输入一个字符串,将字符串的空格替换成%20
- 把字符串中的每个空格替换程“%20”,例如输入“I love my hometown”,输出为”I%20love%20my%20hometown”
- 实现一个函数,把字符串中的每个空格替换成”%20”
- 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 空格替换 请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。 给定一
- 题目:请实现一个函数,将一个字符串中的空格替换成“%20”
- java 把字符串中所有的空格替换为%20 及扩展
- 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
- 把字符串中的每个空格替换程“%20”,例如输入“I love my hometown”,输出为”I%20love%20my%20hometown”
- 替换空格-请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 面试4之字符串中的空格全部替换为“%20”
- 字符串中空格替换为%20(算法)
- 1.5-替换字符串中的空格为%20
- 把字符串中的每个空格替换程“%20”,例如输入“I love my hometown”,输出为”I%20love%20my%20hometown”
- Arrays_Strings 把字符串中所有的空格替换为%20 @CareerCup
- 《剑指offer》-将一个字符串中的空格替换成“%20”
- 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
- 【我的算法日记】请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“We are happy.”,则输出“We%20are%20happy.”。
- 替换字符串中空格为%20