共計 885 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,trim() 函數用于刪除字符串前后的空格。以下是 trim() 函數的用法:
- 刪除前導和尾隨空格:
String str = "Hello World";
String trimmedStr = str.trim();
System.out.println(trimmedStr); // 輸出:Hello World
- 刪除字符串中的所有空格:
String str = "Hello World";
String trimmedStr = str.replace("","");
System.out.println(trimmedStr); // 輸出:HelloWorld
- 刪除字符串中指定位置的空格:
String str = "Hello World";
String trimmedStr = str.replaceAll("\\s+", "");
System.out.println(trimmedStr); // 輸出:HelloWorld
- 刪除字符串前導的空格:
String str = "Hello World";
int start = 0;
while (start < str.length() && str.charAt(start) == ' ') {start++;}
String trimmedStr = str.substring(start);
System.out.println(trimmedStr); // 輸出:Hello World
- 刪除字符串尾隨的空格:
String str = "Hello World";
int end = str.length() - 1;
while (end >= 0 && str.charAt(end) == ' ') {end--;}
String trimmedStr = str.substring(0, end + 1);
System.out.println(trimmedStr); // 輸出:Hello World
需要注意的是,trim() 函數只能刪除字符串前后的空格,無法刪除字符串中間的空格,如果希望刪除所有空格,可以使用 replaceAll() 函數或者 replace() 函數結合正則表達式的方式。
丸趣 TV 網 – 提供最優質的資源集合!
正文完