题目描述
- 请编写一个方法,将字符串中的空格全部替换为“%20”。假定该字符串有足够的空间存放新增的字符,并且知道字符串的真实长度(小于等于1000),同时保证字符串由大小写的英文字母组成。给定一个string iniString 为原始的串, 返回替换后的string。
- 测试样例:
"Mr John Smith”
返回:“Mr%20John%20Smith”
”Hello World”
返回:”Hello%20%20World”
代码
public static void main(String[] args) {
String s="Mr John Smith";
replaceAllSpace2(s);
}
private static void replaceAllSpace2(String s) {
char[] chars = s.toCharArray();
System.out.println(Arrays.toString(chars));
int newArrLength=s.length();
for (int i = 0; i <chars.length ; i++) {
if (chars[i] ==' '){
newArrLength=newArrLength+2;
}
}
char[] newChars=new char[newArrLength];
int p1=chars.length-1;
int p2=newArrLength-1;
System.out.println(p1);
System.out.println(p2);
for (int i = p1; i >=0; i--) {
if(chars[i]==' '){
newChars[p2--]='0';
newChars[p2--]='2';
newChars[p2--]='%';
}else {
newChars[p2--]=chars[i];
}
}
System.out.println(Arrays.toString(newChars));
}
private static void replaceAllSpace(String s) {
String s2 = s.replace(" ", "%20");
System.out.println(s2);
String s1 = s.replaceAll(" ", "%20");
System.out.println(s1);
}