如何在 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
廣告