您的位置:首页 > 其它

替换字符串中的空格

2018-03-12 22:32 162 查看
题目描述:请实现一个函数,将字符串的每个空格替换为"%20"。例如输入"We are happy",则输出"We%20are%20happy."。
思路:从后往前复制,数组长度会增加,或使用StringBuilder、StringBuffer类

        使用StringBuilder、StringBuffer类相当于构建一个新的字符串,将原来的字符串按照顺序依次添加到新的字符串中。
package Problem4;

public class ReplaceBank {

    /*
     * 题目描述: 请实现一个函数,将字符串的每个空格替换为"%20"。
     * 例如输入"We are happy",则输出"We%20are%20happy."。
     */
    /**
     * @param args
     */
    public String replace(String input) {
        StringBuilder builder = new StringBuilder();
        if (input == null || input.length() == 0) {
            return null;
        }
        for (int i = 0; i < input.length(); i++) {
            if (input.charAt(i) == ' ') {
                builder.append("%");
                builder.append("2");
                builder.append("0");
            } else {
                builder.append(input.charAt(i));
            }
        }
        return builder.toString();
    }

    // 测试用例
    public static void main(String[] args) {
        ReplaceBank test = new ReplaceBank();
        // 输入的字符串包含空格:最后面,最前面,中间,连续空格
        String str1 = "We are happy.";
        String str2 = " Wearehappy.";
        String str3 = "Wearehappy. ";
        String str4 = "We   are   happy  .";
        //输入的字符串没有空格
        String str5="Wearehappy.";
        //特殊输入测试:字符串只有连续空格、只有一个空格、字符串是一个null指针、字符串是一个空字符串;
        String str6="    ";
        String str7=" ";
        String str8=null;
        String str9="";
        System.out.println(test.replace(str1));
        System.out.println(test.replace(str2));
        System.out.println(test.replace(str3));
        System.out.println(test.replace(str4));
        System.out.println(test.replace(str5));
        System.out.println(test.replace(str6)
4000
);
        System.out.println(test.replace(str7));
        System.out.println(test.replace(str8));
        System.out.println(test.replace(str9));
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: