如何在 Java 中替换 String 和 StringBuffer 的特定部分?

java 8object oriented programmingprogramming更新于 2025/4/15 7:37:17

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

字符串对象是不可变的,一旦创建字符串对象,就无法更改其值,如果您尝试这样做而不是更改值,则会创建一个具有所需值的新对象,并且引用将转移到新创建的对象,而前一个对象则未使用。

当需要对字符串进行大量修改时,将使用 StringBuffer(和 StringBuilder)类。

与字符串不同,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 类的 replace() 方法接受两个字符串值 −

  • 一个表示要替换的字符串部分(子字符串)。

  • 另一个表示需要替换指定子字符串的字符串。

使用此方法,您可以替换 Java 中字符串的一部分。

示例

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() 方法接受 −

  • 两个整数值,表示要替换的子字符串的起始和终止位置。

  • 应使用其替换上述指定子字符串的字符串值。

使用此方法,您可以将 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

相关文章