從String中移除空白字元的多種方式!?
- 2020 年 9 月 7 日
- 筆記
字元串,是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:本文程式碼都是使用在線運行工具(//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來標識空格字元。你可以在//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,再來對比下他們的區別:
|trim|strip| |—|—| Java 1引入|Java 11引入 使用ASCII|使用Unicode值 刪除開頭和結尾的空白字元|刪除開頭和結尾的空白字元 刪除ASCII值小於或等於’ U+0020 ‘或’ 32 ‘的字元|根據unicode刪除所有空格字元
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進行判斷。
本文由部落格一文多發平台 OpenWrite 發布!