共計 439 個字符,預計需要花費 2 分鐘才能閱讀完成。
有兩種常用的方法來刪除 Java 字符串中的某個字符:
- 使用 substring() 方法:
String str = "Hello World";
char charToRemove = 'o';
int index = str.indexOf(charToRemove);
if(index != -1) {str = str.substring(0, index) + str.substring(index + 1);
}
System.out.println(str); // 輸出 "Hell World"
- 使用 replace() 方法:
String str = "Hello World";
char charToRemove = 'o';
str = str.replace(String.valueOf(charToRemove), "");
System.out.println(str); // 輸出 "Hell Wrld"
這兩種方法都可以刪除指定的字符,可以根據具體需求選擇使用哪種方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完