java,在字符串中的重复字符之间插入

时间:2018-12-10 09:03:11

标签: java string

编写Java程序,在每个紧挨着的重复字母之间插入“#”。 例如 给定以下字符串“ Hello world”,输出应为“ Hel#lo world”

    String str = "Hello java world";

    char a = '#';

    for (int i=0; i<str.length(); i++ ) {
            if (str.charAt(i) == str.charAt(i+1)){
                String temp = str + a;
                System.out.println(temp);
            }
    }

1 个答案:

答案 0 :(得分:0)

好吧,您可以尝试:

示例1:使用REGEX

public static void main(String[] args) {
        String text = "Hello worlld this is someething cool!";
        //add # between all double letters
        String processingOfText = text.replaceAll("(\\w)\\1", "$1#$1");
        System.out.println(processingOfText);

    }

示例2:使用字符串操作

public static void main(String[] args) {
        String text = "Hello worlld this is someething cool!";
        for (int i = 1; i < text.length(); i++) 
        {
            if (text.charAt(i) == text.charAt(i - 1)) 
            {
                text = text.substring(0, i) + "#" + text.substring(i, text.length());
            }
        }
        System.out.println(text);

    }

还有更多...