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!
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP