【问题标题】:Java - Replace one character with multiple charactersJava - 用多个字符替换一个字符
【发布时间】:2014-11-02 23:47:56
【问题描述】:

我一直在尝试用多个字符替换一个字符。 目前我有这个:

public class MainClass {

public static void main(String[] arg) {

    String test = "This is a test.";
    String output = test.replace('i', '!');
    System.out.println(output);
  }

}

问题是我想用“gheri”替换“i”。我一直在尝试将 2+ 个字符放在第二个参数中,但它不起作用。我只能将其更改为长度为 1 个字符的内容。有什么办法吗?

【问题讨论】:

    标签: java replace parameters character


    【解决方案1】:

    String 有一个重载的replace 方法,它接受Strings 而不是字符

    String output = test.replace("i", "gheri");
    

    【讨论】:

      【解决方案2】:

      您可以使用Stringreplace(CharSequence,CharSequence) 之类的,

      public static void main(String[] args) {
          String test = "This is a test.";
          String output = test.replace("i", "gheri");
          System.out.println(output);
      }
      

      输出是

      Thgheris gheris a test.
      

      【讨论】:

      • 对于未来的读者来说,诀窍在于 char 序列的双引号与 char 的单引号。
      猜你喜欢
      • 2020-07-12
      • 2013-12-05
      • 1970-01-01
      • 2017-02-24
      • 2021-06-08
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      相关资源
      最近更新 更多