剑指offer:替换空格(java)

/**
 * 题目:
 *      请实现一个函数,将一个字符串中的每个空格替换成“%20”。
 *      例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
 */
public class P51_ReplaceBlank {
    public String RplaceBlank(StringBuffer str) {
        StringBuffer temp = new StringBuffer();

        if (str == null || str.length() == 0) {
            return temp.toString();
        }


        for(int i=0;i<str.length();i++){
            if (str.charAt(i) == ' ') {
                temp.append('%');
                temp.append('2');
                temp.append('0');
            }
            else
                temp.append(str.charAt(i));
        }
        String result = temp.toString();
        return result;
    }

    public char[] replaceBlank(char[] str){
        if (str == null || str.length == 0) {
            return null;
        }

        int count = 0;
        for (int i = 0; i < str.length; i++) {
            if (str[i] == ' ') {
                count++;
            }
        }

        char[] Nstr = new char[str.length + count * 2];
        for (int i = 0, j = 0; i < str.length & j < Nstr.length; i++, j++) {
            if (str[i] == ' ') {
                Nstr[j++] = '%';
                Nstr[j++] = '2';
                Nstr[j] = '0';
            }
            else
                Nstr[j] = str[i];
        }
        String result = Nstr.toString();
        //return result;
        return Nstr;
    }

    public static void main(String[] args) {
        StringBuffer str = new StringBuffer("");
        P51_ReplaceBlank test = new P51_ReplaceBlank();
        char[] str1 = {'w', 'e',' ', 'a', 'r', 'e',' ', 'h', 'a', 'p', 'p', 'y'};
        //String result = test.replaceBlank(str1);
        //char[] temp = new char[result.length()];
        //temp = result.toCharArray();
        char[] temp = test.replaceBlank(str1);

        for (int i = 0; i < temp.length; i++) {
            System.out.print(temp[i]);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Sunshine_liang1/article/details/82463085