問題
首先我們先假設需要對一個字符串"hello world!"
做分割,去除中間的空格,獲取每一個單詞的字符串數組words。
方法1
我們最簡單也是最容易的方法是使用split
對字符串進行分割。
方法如下:
String s = "hello world!";
String[] words = s.split(" ");
for(String word:words){
System.out.println(word);
}
打印結果如下:
hello
world!
但是這樣的方法在面對多個空格時將會獲取空的字符串。例如
String s = "hello world!";
String[] words = s.split(" ");
for(String word:words){
System.out.println(word);
}
打印結果如下:
hello
world!
顯然這種方式不合我們的預期,接下來我們考慮使用功能更強大一些的正則表達式來達成我們的目標。
方法二
正則表達式\\s+
表示匹配任何空白字符一次或多次。我們使用一個更長一點的字符串進行測試:
String str = "hello world! this is right!";
String[] words = str.split("\\s+");
for(String word:words){
System.out.println(word);
}
打印結果如下:
hello
world!
this
is
right!
可以看到,目前使用正則表達式進行字符串的切分達到了我們的目的。我們再來考慮一種情況,在這個字符串的開頭或者結尾處也同樣含有空格的情況。例如:
String str = " hello world! this is right! ";
String[] words = str.split("\\s+");
for(String word:words){
System.out.println(word);
}
System.out.println("-------this is endLine-------");
打印結果如下:
hello
world!
this
is
right!
-------this is endLine-------
可以看到,開頭的空格並沒有被正確切分出來,使用正則表達式也沒有達到我們的目的。
方法3
其實,從方法2來看,我們已經很接近了,只是開頭這空格有些令人惱怒。也許聰明的你已經在想,假如我能在進行分割之前把字符串的開頭空格給處理掉,這樣再使用split
分割不就好了?Java的String方法中確實有這樣一個方法能夠辦到這件事,看來你和Java語言的設計者所見略同。前面提到的方法叫trim
,知道這件事后,接下來就好辦了。
我們來測試一下:
String str = " hello world! this is right! ";
String afterTrim = str.trim();
System.out.println("after trim:"+afterTrim);
String[] words = afterTrim.split("\\s+");
for(String word:words){
System.out.println(word);
}
System.out.println("-------this is endLine-------");
打印結果如下:
after trim: hello world! this is right!
hello
world!
this
is
right!
-------this is endLine-------
使用trim
,split
,正則表達式后,我們完成了對一個字符串去除了空格並提取分隔的單詞信息。
獲取不含空格字符串
這里簡單介紹一下,主要的思路是使用String對象提供的replaceAll方法,這里只給出一種簡單實現,更多可以去參考文章中自行參閱。
String str = " hello world! this is right! ";
System.out.println(str.replaceAll(" +",""));
打印結果如下:
helloworld!thisisright!
上述方法可以去除字符串中的所有空格,包括開頭結尾,並返回一個String。
總結
在對一個簡單字符串"hello world!"的切分中,我們首先使用了方法1,簡單的使用split進行切分,但這種方式無法處理含多個空格間隔的單詞切分;這時我們開始求助於方法二,也就是使用正則表達式進行切分,雖然效果很好,但是在這種方法在面對字符串開頭含空格的情況下無法正確切割掉開頭的空格;最后,我們使用方法3,也就是用trim先對字符串做預處理,消除開頭結尾的空格之后再做切分,這樣,我們完美完成了我們的任務。
最后文章稍微提了一下對於獲取不含空格的字符串的方法。
參考文章: