共計 459 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用以下方法去除字符串中的空格:
- 使用
trim()
方法去除字符串兩端的空格:
String str = " hello world ";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // 輸出: "hello world"
- 使用
replaceAll()
方法去除字符串中所有空格:
String str = " hello world ";
String noSpaceStr = str.replaceAll("\\s", "");
System.out.println(noSpaceStr); // 輸出: "helloworld"
- 使用
replace()
方法去除字符串中所有空格:
String str = " hello world ";
String noSpaceStr = str.replace(" ", "");
System.out.println(noSpaceStr); // 輸出: "helloworld"
這些方法可以根據具體需求選擇使用哪種去除空格的方式。
丸趣 TV 網 – 提供最優質的資源集合!
正文完