首页 文章

java,在String中的重复字符之间插入[暂停]

提问于
浏览 1739
-8

编写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

    好吧,你可以尝试:

    Example 1: Using 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);
    
        }
    

    Example 2: Using string manipulations

    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);
    
        }
    

    还有更多......

相关问题