替换空格 4
先遍历每个字符统计空格数 :String.charAt()
根据空格数计算新的长度 :newLength=oriLength+2*NumOfBlank
新建一个newLength长度的字符数组tempChars用于存放替换空格之后的字符数组
利用System.arraycopy函数将原字符串转换为数组拷贝到新的字符数组tempChars中
从新字符数组末尾开始遍历,用一个index1指向新字符数组末尾,用一个index2指向原字符数组末尾所在新字符数组的位置,将原字符数组逐个复制到新的字符数组的位置,遇到空格,替换,此时index1动,index2不动
复杂度O(n),如果是从前往后复制的话复杂度O(n^2)
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);
}
}