CCI 1.4 将字符串空格替换成“%20”

编写一个方法,将字符串中的空格全部替换为“%20”。

package test;

public class ReplaceSpace {

	public static char[] replace(char[] str){
		if(str==null || str.length==0)
			return str;
		int count = 0;
		for(char item : str)
			if(item==' ')
				count++;
		int newLength = str.length + 2*count;
		char[] newStr = new char[newLength];
		for(int i=str.length-1; i>=0; i--){
			if(str[i] == ' '){
				newStr[newLength-1] = '0';
				newStr[newLength-2] = '2';
				newStr[newLength-3] = '%';
				newLength -= 3;
			}else{
				newStr[newLength-1] = str[i];
				newLength -= 1;
			}
		}
		str = newStr;
		return str;
	}
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		char[] case1 = null;
		char[] case2 = new char[0];
		char[] case3 = {'a', ' ', 'b'};
		char[] case4 = {' ', ' ', ' '};
		
		char[] result = replace(case3);
		System.out.println(result);
	}

}


你可能感兴趣的:(字符串,数组)