我们如何替换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进行大量修改,则使用StringBuffer(和StringBuilder)类。

与Strings不同,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()方法接受两个String值-

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

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

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

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