1. 程式人生 > >劍指offer面試題5:替換空格

劍指offer面試題5:替換空格

題目:請實現一個函式,把字串中的每個空格替換成%20。例如,輸入“we are happy”,則輸出“we%20are%20happy"

public class Test {
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		String str = "We are happy";
		System.out.println(transform(str));
		long endTime = System.currentTimeMillis() - startTime;
		System.out.println(endTime);
	}
//使用StringBuilder的repalce方法
	private static String transform(String str) {
		String replaceStr = "%20";
		int length = str.length();
		StringBuilder builder = new StringBuilder(str);
		for (int i = 0; i < length; i++) {
			if (' ' == builder.charAt(i)) {
				builder.replace(i, i + 1, replaceStr);
				length = length+replaceStr.length() - 1;
			}
		}
		return builder.toString();
	}

}

假設我們不使用StringBuilder的Replace方法:

private static String transform(StringBuilder str) {
		return str.toString().replaceAll("\\s", "%22");
	}