共計 547 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用以下方法來去掉字符串中的某些字符:
- 使用 replaceAll() 方法:該方法使用正則表達式來替換字符串中的字符。
String str = "Hello, World!";
String newStr = str.replaceAll("[,]", "");
System.out.println(newStr); // Output: HelloWorld!
- 使用 replace() 方法:該方法用新的字符替換字符串中的舊字符。
String str = "Hello, World!";
String newStr = str.replace(",", "").replace(" ", "");
System.out.println(newStr); // Output: HelloWorld!
- 使用 substring() 方法:該方法返回字符串中指定位置的子字符串。
String str = "Hello, World!";
String newStr = str.substring(0, 5) + str.substring(7);
System.out.println(newStr); // Output: HelloWorld!
這些方法都可以根據具體需求選擇使用,根據實際情況選擇最適合的方法來去掉字符串中的某些字符。
丸趣 TV 網 – 提供最優質的資源集合!
正文完