Write a method to replace all spaces in a string with ‘%20’.
You can not put '%20' directly into a string, and the size of new string doesn't equal to old string.
public class ccChap1_5 {
public static void main(String[] args){
String st = "ABCD AB C D ";
System.out.println(strReplace(st));
}
public static String strReplace(String str){
int count=0;
int newLen=0;
for(int i=0; i<str.length();i++){
if(str.charAt(i)==' '){
count++;
}
}
char[] ch = new char[str.length()+count*2];
for(int i=0; i<str.length();i++){
if(str.charAt(i)==' '){
ch[newLen]='%';
ch[newLen+1]='2';
ch[newLen+2]='0';
newLen=newLen+3;
}else {
ch[newLen]=str.charAt(i);
newLen++;
}
}
return new String(ch);
}
}