题目:
请编写一个方法,将字符串中的空格全部替换为“%20”"。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。
给定一个string iniString 为原始的串,以及串的长度 int len,返回替换后的string。测试样例;
"Mr John Smith",13
返回:“Mr%20John%20Smith ”
”Hello World",12
返回:”Hello%20%20World"
思路:
1.直接使用Java的API
2.先算空格数组,每扫描到一个空格,字符数组大小+2
package 字符串问题;
public class case04_替换空格 {
public static void main(String[] args) {
char[] s="Hello World00000".toCharArray();
System.out.println(replaceSpace(s,12));
}
private static String replaceSpace(char[] s, int length) {
//计算空格数
int count=length;//计算替换后总的数组长度
for(int i=0;i<length;i++){
if(s[i]==' '){
count+=2;
}
}
int p1=length-1;//扫描原数组
int p2=count-1;//添加%20
while(p1>0){
if (s[p1] == ' ') {
s[p2--]='0';
s[p2--]='2';
s[p2--]='%';
}else{
s[p2--]=s[p1];
}
p1--;
}
return new String(s,0,count);
}
}