【问题标题】:java , inserting between duplicate chars in String [closed]java,在字符串中的重复字符之间插入[关闭]
【发布时间】:2019-05-11 03:46:23
【问题描述】:

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

【问题讨论】:

  • 您是否尝试过编写一些代码? Stack Overflow 不是免费的代码编写服务。
  • 欢迎来到 StackOverflow!您实际上并没有提出问题,也没有展示您为尝试解决此问题而编写的代码。 Please have a look at this introductory page.
  • 感谢您向我们展示您的代码。它有什么作用?如果它没有做你想让它做的事情,是否有什么具体的事情你不明白为什么它会做它做的事情?
  • 这段代码显然会抛出一个IndexOutOfBoundsException,并且它不会在连续的相同字母之间插入'#'。 @Serii 你为什么不描述你的代码的问题是什么?由于if 状态中使用的条件(str.charAt(i+1) 尝试在循环结束时访问无效索引),Exception 被抛出。

标签: java string


【解决方案1】:

嗯,你可以试试:

示例 1:使用正则表达式

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

    }

还有更多...

【讨论】:

  • 非常感谢 MS90,它工作得很好!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 2012-12-14
相关资源
最近更新 更多