學習使用String
類的strip()
, stripLeading()
和 stripTrailing()
方法來刪除不需要的空格來自 Java 11 中的給定字符串。
字符串strip()
從Java 11開始,String
類包含3個其他方法,這些方法有助於消除多余空格。使用 Character.isWhitespace(char) 方法來確定空白字符。
- String strip() – 返回一個字符串,其值指定為字符串,並且所有左右空格都已刪除。
- String stripLeading() – 返回其值為字符串的字符串,其中所有左空白都已刪除。
- String stripTrailing() – 返回其值為字符串的字符串,並刪除所有右空白。
public class Main { public static void main(String[] args) { String str = " Hello World !! "; System.out.println( str.strip() ); //"Hello World !!" System.out.println( str.stripLeading() ); //"Hello World !! " System.out.println( str.stripTrailing() ); //" Hello World !!" } }
正則去除空白
在不使用Java 11的情況下,可以使用正則表達式來修剪字符串周圍的空格。
正則表達式 | 說明 |
---|---|
^ [\t] + | [\t] + $ | 刪除前導空格和尾隨空格 |
^ [\t] + | 僅刪除前導空白 |
[\t] + $ | 僅刪除尾隨空格 |
public class Main { public static void main(String[] args) { String str = " Hello World !! "; System.out.println( str.replaceAll("^[ \t]+|[ \t]+$", "") ); //"Hello World !!" System.out.println( str.replaceAll("^[ \t]+", "") ); //"Hello World !! " System.out.println( str.replaceAll("[ \t]+$", "") ); //" Hello World !!" } }
鏈接:https://www.learnfk.com/article-java11-strip-remove-white-spaces
來源:Learnfk無涯教程