先遍历一遍字符串,找出空格个数,计算出新字符串的长度,从尾到头处理,减少字符移动
/** * Created by itworker365 on 5/12/2017. */ public class Main { public static void main(String[] args) { Main solution = new Main(); StringBuffer sb = new StringBuffer(); sb.append("this is test"); String res = solution.replaceSpace(sb); System.out.println(res); } public String replaceSpace(StringBuffer str) { int spaceCnt = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if ((int)c == 32) { spaceCnt++; } } char[] temp = new char[str.length() + spaceCnt*2]; System.out.println(spaceCnt); int tempIdx = temp.length - 1; for (int i = str.length() - 1; i >= 0; i--) { char c = str.charAt(i); if ((int)c == 32) { temp[tempIdx--] = '0'; temp[tempIdx--] = '2'; temp[tempIdx--] = '%'; } else { temp[tempIdx--] = c; } } return new String(temp); } }