总结
首先遍历字符串,得到字符串中的空格数,用到String的charAt方法
然后计算得到新字符char数组的长度,等于原字符长度加上两倍的空格数
再将字符串转换为字符数组移到result字符数组中,用到System.arraycopy函数
然后定义两个index,分别指向原字符长度的尾巴,以及新字符长度的尾巴
int indexOfOrgChars=orgLength-1;
int indexOfNewChars=newLength-1;
从后往前移动,这样可以保证移动字符的数目最少,遇到空格字符,把%20插入,这时候只有indexOfNewChars动,而indexOfOriChars不动
非空格字符,两个index都动
package replaceBlank;
public class ReplaceBlank {
public static int getBlankNum(String testString) {
int count = 0;
for (int i = 0; i < testString.length(); i++) {
String tempString = String.valueOf(testString.charAt(i));
if (tempString.equals(" ")) {
count++;
}
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String string = "we are here";
replaceBlank(string);
}
static void replaceBlank(String string){
if (string==null) {
return;
}
int orgLength=string.length();
int numOfBlank=0;
for (int i = 0; i < string.length(); i++) {
String tempString = String.valueOf(string.charAt(i));
if (tempString.equals(" ")) {
numOfBlank++;
}
}
int newLength=orgLength+2*numOfBlank;
char[] tempChars=new char[newLength];
System.arraycopy(string.toCharArray(), 0, tempChars, 0, string.length());
System.out.println("orgLength:"+orgLength+"\n"+"numOfBlank:"+numOfBlank);
int indexOfOrgChars=orgLength-1;
int indexOfNewChars=newLength-1;
while (indexOfOrgChars>=0&&indexOfNewChars!=indexOfOrgChars) {
if (tempChars[indexOfOrgChars]==' ') {
tempChars[indexOfNewChars--]='%';
tempChars[indexOfNewChars--]='2';
tempChars[indexOfNewChars--]='0';
}else {
tempChars[indexOfNewChars--]=tempChars[indexOfOrgChars];
}
indexOfOrgChars--;
}
System.out.println(tempChars);
}
}