如何在 Java 中替换 String 和 StringBuffer 的特定部分?
java.lang 包中的String类表示一组字符。Java 程序中的所有字符串字面量,例如“abc”,都作为此类的实例实现。
示例
在线演示
public class StringExample {
public static void main(String[] args) {
String str = new String("Hello how are you");
System.out.println("Contents of the String: "+str);
}
}输出
Hello how are you
String 对象是不可变的,一旦创建 String 对象,就无法更改其值,如果尝试这样做,则不会更改值,而是会创建一个具有所需值的新对象,并且引用会转移到新创建的对象,留下先前未使用的对象。
当需要对 String 进行大量修改时,使用StringBuffer(和 StringBuilder)类。
与 String 不同,StringBuffer 类型的对象可以反复修改,而不会留下大量新的未使用的对象。它是一个线程安全的、可变的字符序列。
示例
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer();
buffer.append("Hello ");
buffer.append("how ");
buffer.append("are ");
buffer.append("you");
System.out.println("Contents of the string buffer: "+buffer);
}
}输出
Contents of the string buffer: Hello how are you
替换 String 的特定部分
String 类的 replace() 方法接受两个 String 值 -
一个表示要替换的 String 部分(子字符串)。
另一个表示需要替换指定子字符串的 String。
使用此方法,您可以在 Java 中替换 String 的一部分。
示例
public class StringReplace {
public static void main(String[] args) {
String str = new String("Hello how are you, welcome to TutorialsPoint");
System.out.println("Contents of the String: "+str);
str = str.replace("welcome to TutorialsPoint", "where do you live");
System.out.println("Contents of the String after replacement: "+str);
}
}输出
Contents of the String: Hello how are you, welcome to TutorialsPoint Contents of the String after replacement: Hello how are you, where do you live
替换 StringBuffer 的特定部分
类似地,StringBuffer 类的 replace() 方法接受 -
两个整数,分别表示要替换的子字符串的起始和结束位置。
一个 String 值,用它来替换上面指定的子字符串。
使用此方法,您可以用所需的 String 替换 StringBuffer 的子字符串。
示例
public class StringBufferReplace {
public static void main(String[] args) {
StringBuffer buffer = new StringBuffer();
buffer.append("Hello ");
buffer.append("how ");
buffer.append("are ");
buffer.append("you ");
buffer.append("welcome to TutorialsPoint");
System.out.println("Contents of the string buffer: "+buffer);
buffer.replace(18, buffer.length(), "where do you live");
System.out.println("Contents of the string buffer after replacement: "+buffer);
}
}输出
Contents of the string buffer: Hello how are you welcome to TutorialsPoint Contents of the string buffer after replacement: Hello how are you where do you live
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP