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]); } } }