【问题标题】:Replace more than one continuous occurrence of underscore character "_" with the string "blank"将多次连续出现的下划线字符“_”替换为字符串“blank”
【发布时间】:2019-02-08 20:16:39
【问题描述】:

我需要用单词blank 替换任何字符串中不止一个连续重复的字符_,这样This_is a test ___ 就会变成This_is a test blank。如果只有一个_ 字符,则不应替换。

需要将多个连续的下划线替换为空白,以便在android中读取字符串以进行文本转语音时说出单词blank。

【问题讨论】:

    标签: java android string replace character


    【解决方案1】:

    您可以使用Regular Expression 来完成此操作。幸运的是,String 上有一个名为 replaceAll() 的方法,它采用正则表达式:

    final String input = "This_is a test ___";
    final String output = input.replaceAll("_{2,}", "blank");
    System.out.println(output);  // Prints "This_is a test blank"
    

    那里的表达的意思是:“找到至少 2 个连续出现的下划线”。

    【讨论】:

      【解决方案2】:

      您可以使用replaceAll() 方法:

      String str = "This_ is a ____";
      str = str.replaceAll("[_]{2,}", "blank");
      

      输出:

      This_ is a blank
      

      【讨论】:

        猜你喜欢
        • 2018-02-24
        • 1970-01-01
        • 1970-01-01
        • 2018-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-31
        • 1970-01-01
        相关资源
        最近更新 更多