we are happy 把空格换成 %20 剑指offer P44

public class StringReplace {
public static void replaceSpace(String[] str, int length) {
if(str == null || length <= 0) {
return;
}
int originalLength = 0;
int numberOfBlank = 0;
int i = 0;
while(str[i] != null) {
originalLength ++;
if(str[i] == " ") {
numberOfBlank ++;
}
i++;
}
//新的字符串长度
int newLength = originalLength + 2 * numberOfBlank;
if(newLength > length) {//不能超出字符数组的长度
return;
}
int originalIndex = originalLength-1;
int newIndex = newLength-1;
while(originalIndex >=0 && originalIndex < newIndex) {
if(str[originalIndex] == " ") {
str[newIndex--] = "0";
str[newIndex--] = "2";
str[newIndex--] = "%";
originalIndex --;
}else {
str[newIndex--] = str[originalIndex--];
} } } public static void main(String[] args) {
String[] temp = {"we", " ","are", " ", "happy",null,null,null,null,null,null,null,null };
replaceSpace(temp,13);
for(int i=0; i< temp.length; i ++) {
System.out.print(temp[i]);
}
} }
上一篇:Android String format 通过value 下的string.xml 文件


下一篇:CentOS 6.5 64位 安装zabbix-2.2.0