從String中移除空白字符的多種方式!?差別竟然這麼大!


字符串,是Java中最常用的一個數據類型了。我們在日常開發時候會經常使用字符串做很多的操作。比如字符串的拼接、截斷、替換等。
這一篇文章,我們介紹一個比較常見又容易被忽略的一個操作,那就是移除字符串中的空格。
其實,在Java中從字符串中刪除空格有很多不同的方法,如trim,replaceAll等。但是,在Java 11添加了一些新的功能,如strip、stripLeading、stripTrailing等。
大多數時候,我們只是使用trim方法來刪除多餘的空格。但是好像很多人並沒有去思考過,是否有更好的方式呢?
當然,trim()在大多數情況下都工作得很好,但是Java中有許多不同的方法。每一種都有自己的優點和缺點。我們如何決定哪種方法最適合我們呢?
接下來我們將介紹幾種方法,並對比下他們的區別和優缺點等。



在java中從字符串中刪除空格的不同方法
首先,我們來看一下,想要從String中移除空格部分,有多少種方法,作者根據經驗,總結了以下7種(JDK原生自帶的方法,不包含第三方工具類庫中的類似方法):
  • trim() : 刪除字符串開頭和結尾的空格。
  • strip() : 刪除字符串開頭和結尾的空格。
  • stripLeading() : 只刪除字符串開頭的空格
  • stripTrailing() : 只刪除字符串的結尾的空格
  • replace() : 用新字符替換所有目標字符
  • replaceAll() : 將所有匹配的字符替換爲新字符。此方法將正則表達式作爲輸入,以標識需要替換的目標子字符串
  • replaceFirst() : 僅將目標子字符串的第一次出現的字符替換爲新的字符串
需要注意的最重要的一點是,在Java中 String對象是不可變 的,這意味着我們不能修改字符串,因此以上所有的方法我們得到的都是一個新的字符串。
接下啦,我們分別針對以上這幾個方法學習下用法,瞭解下其特性。
PS:本文代碼都是使用在線運行工具(https://www.jdoodle.com/online-java-compiler/ )執行的,因爲我的測試機並未安裝Java 11,並且Unicode字符也不完整。如果大家也想實驗,建議使用在線工具,選擇對應的JDK即可。



trim
trim()是Java開發人員最常用的刪除字符串開頭和結尾的空格方法。其用法也比較簡單:

public class StringTest {

    public static void main(String[] args{

        String stringWithSpace = "   Hollis   Is   A   Java   Coder   ";

        StringTest.trimTest(stringWithSpace);

    }

    private static void trimTest(String stringWithSpace){

        System.out.println("Before trim : \'" + stringWithSpace + "\'");

        String stringAfterTrim = stringWithSpace.trim();

        System.out.println("After trim : \'" + stringAfterTrim + "\'");

    }

}

輸出結果:

Before trim : '   Hollis   Is   A   Java   Coder   '

After trim : 'Hollis   Is   A   Java   Coder'

如上,使用trim之後,原字符串中開頭和結尾部分的空格內容都被移除掉了。
但是不知道大家有沒有思考過,trim方法移除的空白內容都包含哪些東西?除了空格以外,還有其他的字符嗎?
其實,trim移除的空白字符指的是指ASCII值小於或等於32的任何字符(' U+0020 ')
其中包含了空格、換行、退格等字符。



strip()
不知道大家有沒有注意到,在Java 11的發行版中,添加了新的strip()方法來刪除字符串中的前導和末尾空格。
已經有了一個trim方法,爲什麼還要新增一個strip呢?
這其實是是因爲trim方法只能針對ASCII值小於等於32的字符進行移除,但是根據Unicode標準,除了ASCII中的字符以外,還是有很多其他的空白字符的。
而且爲了識別這些空格字符,從Java 1.5開始,還在Character類中添加了新的isWhitespace(int)方法。該方法使用unicode來標識空格字符。你可以在http://jkorpela.fi/chars/spaces.html 瞭解更多關於unicode空格字符的信息。
而在Java 11中新增的這個strip方法就是使用這個Character.isWhitespace(int)方法來判斷是否爲空白字符並刪除它們的:
下面我們來看一個使用strip例子:

public class StringTest {

    public static void main(String args[]{

      String stringWithSpace ='\u2001' + "  Hollis   Is   A   Java   Coder  " + '\u2001';

        System.out.println("'" + '\u2001' + "' is space : " +  Character.isWhitespace('\u2001'));

        StringTest.stripTest(stringWithSpace);

    }

    private static void stripTest(String stringWithSpace){

        System.out.println("Before strip : \'" + stringWithSpace + "\'");

        String stringAfterTrim = stringWithSpace.strip();

        System.out.println("After strip : \'" + stringAfterTrim + "\'");

    }

}

我們在字符串前後都增加了一個特殊的字符\u2001,這個字符是不在ASCII中的,經過Character.isWhitespace判斷他是一個空白字符。然後使用strip進行處理,輸出結果如下:

' ' is space : true

Before strip : '   Hollis   Is   A   Java   Coder   '

After strip : 'Hollis   Is   A   Java   Coder'

所以,Java 11 中的 strip 方法要比trim方法更加強大,他可以移除很多不在ASCII中的空白字符,判斷方式就是通過Character.isWhitespace方法。



trim 和 strip 方法的區別
上面我們介紹了兩個都可以移除字符串開頭和結尾的方法,分別是trim 和 strip,再來對比下他們的區別:




stripLeading() 和 stripTrailing()
stripLeading()和stripTrailing()方法也都是在Java 11中添加的。作用分別是刪除字符串的開頭的空格以及刪除字符串的末尾的空格。
與strip方法類似,stripLeading、stripTrailing也使用Character.isWhitespace(int)來標識空白字符。用法也和strip類似:

public class StringTest {

    public static void main(String args[]{

      String stringWithSpace ='\u2001' + "  Hollis   Is   A   Java   Coder  " + '\u2001';

        System.out.println("'" + '\u2001' + "' is space : " +  Character.isWhitespace('\u2001'));

        StringTest.stripLeadingTest(stringWithSpace);

        StringTest.stripTrailingTest(stringWithSpace);

    }


    private static void stripLeadingTest(String stringWithSpace){

        System.out.println("Before stripLeading : \'" + stringWithSpace + "\'");

        String stringAfterTrim = stringWithSpace.stripLeading();

        System.out.println("After stripLeading : \'" + stringAfterTrim + "\'");

    }


     private static void stripTrailingTest(String stringWithSpace){

        System.out.println("Before stripTrailing : \'" + stringWithSpace + "\'");

        String stringAfterTrim = stringWithSpace.stripTrailing();

        System.out.println("After stripTrailing : \'" + stringAfterTrim + "\'");

    }

}

輸出結果:

' ' is space : true

Before stripLeading : '   Hollis   Is   A   Java   Coder   '

After stripLeading : 'Hollis   Is   A   Java   Coder   '

Before stripTrailing : '   Hollis   Is   A   Java   Coder   '

After stripTrailing : '   Hollis   Is   A   Java   Coder'




replace
移除字符串中的空白字符,除了使用trim、strip以外,還有一個辦法,那就是使用replace方法把其中的空白字符替換掉。
replace是從java 1.5中添加的,可以用指定的字符串替換每個目標子字符串。
此方法替換所有匹配的目標元素,使用方式如下:

 public class StringTest {

    public static void main(String args[]{

        String stringWithSpace ="  Hollis   Is   A   Java   Coder  ";

        StringTest.replaceTest(stringWithSpace);

    }



    private static void replaceTest(String stringWithSpace){

        System.out.println("Before replace : \'" + stringWithSpace + "\'");

        String stringAfterTrim = stringWithSpace.replace(" """);

        System.out.println("After replace : \'" + stringAfterTrim + "\'");

    }

}

結果:

Before replace : '  Hollis   Is   A   Java   Coder  '

After replace : 'HollisIsAJavaCoder'

可見,以上使用replace方法可以替換掉字符串中的所有空白字符。特別需要注意的是,replace方法和trim方法一樣,只能替換掉ASCII中的空白字符。



replaceAll
replaceAll是Java 1.4中添加的最強大的字符串操作方法之一。我們可以將這種方法用於許多目的。
使用replaceAll()方法,我們可以使用正則表達式來用來識別需要被替換的目標字符內容。使用正則表達式,就可以實現很多功能,如刪除所有空格,刪除開頭空格,刪除結尾空格等等。
我們只需要用正確的替換參數創建正確的正則表達式。一些正則表達式的例子如下:

\s+   所有的空白字符

^\s+      字符串開頭的所有空白字符

\s+$      字符串結尾的所有空白字符

注意,在java中要添加 / 我們必須使用轉義字符,所以對於 \s+ 我們必須使用 \\s+

public class StringTest {

    public static void main(String args[]{

        String stringWithSpace ="  Hollis   Is   A   Java   Coder  ";

        StringTest.replaceAllTest(stringWithSpace," ");

        StringTest.replaceAllTest(stringWithSpace,"\\s+");

        StringTest.replaceAllTest(stringWithSpace,"^\\s+");

        StringTest.replaceAllTest(stringWithSpace,"\\s+$");

    }


    private static void replaceAllTest(String stringWithSpace,String regex){

        System.out.println("Before replaceAll with '"+ regex +"': \'" + stringWithSpace + "\'");

        String stringAfterTrim = stringWithSpace.replaceAll(regex, "");

        System.out.println("After replaceAll with '"+ regex +"': \'" + stringAfterTrim + "\'");

    }

}

結果:

Before replaceAll with ' ''  Hollis   Is   A   Java   Coder  '

After replaceAll with ' ''HollisIsAJavaCoder'

Before replaceAll with '\s+''  Hollis   Is   A   Java   Coder  '

After replaceAll with '\s+''HollisIsAJavaCoder'

Before replaceAll with '^\s+''  Hollis   Is   A   Java   Coder  '

After replaceAll with '^\s+''Hollis   Is   A   Java   Coder  '

Before replaceAll with '\s+$''  Hollis   Is   A   Java   Coder  '

After replaceAll with '\s+$''  Hollis   Is   A   Java   Coder'

正如我們所看到的,如果將replaceAll()與適當的正則表達式一起使用,它將是非常強大的方法。



replaceFirst
replaceFirst方法也是在java 1.4中添加的,它只將給定正則表達式的第一個匹配項替換爲替換字符串。
如果您只需要替換第一次出現的情況,那麼這個方法非常有用。例如,如果我們只需要刪除前導空格,我們可以使用 \\s+ ^\\s+
我們還可以通過使用 \\s+$ 正則表達式使用此方法來刪除末尾空格。因爲這個表達式將只匹配行的最後一個空格。因此最後的空格被認爲是這個方法的第一個匹配。
讓我們舉一個從字符串中刪除前導和尾隨空格的例子

public class StringTest {

    public static void main(String args[]{

        String stringWithSpace ="  Hollis   Is   A   Java   Coder  ";

        StringTest.replaceFirstTest(stringWithSpace," ");

        StringTest.replaceFirstTest(stringWithSpace,"\\s+");

        StringTest.replaceFirstTest(stringWithSpace,"^\\s+");

        StringTest.replaceFirstTest(stringWithSpace,"\\s+$");

    }


    private static void replaceFirstTest(String stringWithSpace,String regex){

        System.out.println("Before replaceFirst with '"+ regex +"': \'" + stringWithSpace + "\'");

        String stringAfterTrim = stringWithSpace.replaceFirst(regex, "");

        System.out.println("After replaceFirst with '"+ regex +"': \'" + stringAfterTrim + "\'");

    }

}

結果:

Before replaceFirst with ' ''  Hollis   Is   A   Java   Coder  '

After replaceFirst with ' '' Hollis   Is   A   Java   Coder  '

Before replaceFirst with '\s+''  Hollis   Is   A   Java   Coder  '

After replaceFirst with '\s+''Hollis   Is   A   Java   Coder  '

Before replaceFirst with '^\s+''  Hollis   Is   A   Java   Coder  '

After replaceFirst with '^\s+''Hollis   Is   A   Java   Coder  '

Before replaceFirst with '\s+$''  Hollis   Is   A   Java   Coder  '

After replaceFirst with '\s+$''  Hollis   Is   A   Java   Coder'




總結
本文介紹了7種移除字符串中的空白字符的方法。
想要直接移除掉字符串開頭的空白字符,可以使用stripLeading、replaceAll和replaceFirst
想要直接移除掉字符串末尾的空白字符,可以使用stripTrailing、replaceAll和replaceFirst
想要同時移除掉字符串開頭和結尾的空白字符,可以使用strip、trim
想要移除掉字符串中的所有空白字符,可以使用replace和replaceAll
而Java 11種新增的strip、stripTrailing以及stripLeading方法,可以移除的字符要比其他方法多,他可以移除的空白字符不僅僅侷限於ASCII中的字符,而是Unicode中的所有空白字符,具體判斷方式可以使用Character.isWhitespace進行判斷。

   
   
   

往期推薦

推薦一款開源數據庫設計工具,比PowerDesigner更好用!


Socket粘包問題的3種解決方案,最後一種最完美!


SpringBoot集成Google開源圖片處理框架,賊好用!


關注我,每天陪你進步一點點!

本文分享自微信公衆號 - Java中文社羣(javacn666)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章