Java 程序仅使用新字符串替换给定字符串的第一个出现


使用 replaceFirst() 方法仅替换给定字符串的第一个出现

假设我们有以下字符串。

String str = "THIS IS DEMO TEXT!";

我们必须将“IS”的第一个出现替换为“EV”。为此,使用 replaceFirst() 方法。

str.replaceFirst("IS", "EV");

以下是由“IS”的第一个出现替换的最终示例。

例子

 实际演示

public class Demo {
   public static void main(String[] args) {
      String str = "THIS IS DEMO TEXT!";
      System.out.println("String = "+str);
      System.out.println("Replacing only the first occurrence of substring IS...");
      System.out.println("Updated string = "+str.replaceFirst("IS", "EV"));
   }
}

输出

String = THIS IS DEMO TEXT!
Replacing only the first occurrence of substring IS...
Updated string = THEV IS DEMO TEXT!

更新于:25-6-2020

237 次浏览

开启您的 事业

完成课程获取证书

开始
广告
© . All rights reserved.