Java中常用的替換字符的方法有以下幾種:
示例代碼:
String str = "Hello World";
String newStr = str.replace("World", "Java");
System.out.println(newStr); // 輸出:Hello Java
示例代碼:
String str = "Hello World";
String newStr = str.replaceAll("[Ww]orld", "Java");
System.out.println(newStr); // 輸出:Hello Java
示例代碼:
String str = "Hello World";
String newStr = str.replaceFirst("[Ww]orld", "Java");
System.out.println(newStr); // 輸出:Hello Java
示例代碼:
StringBuilder sb = new StringBuilder("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb.toString()); // 輸出:Hello Java