用Java拆分字符串示例和技巧 -Dreamix


字符串类提供了一个拆分方法,该方法适用于某些情况。该方法只是通过使用作为参数传递的定界符来分割字符串。参数可以是正则表达式或简单字符。方法签名可以是:

String[]    split​(String regex)

还有一个选项可以添加一个可以为负,正或等于0的limit限制。

String[]    split​(String regex, int limit)

  • 如果limit限制具有正值,则将在最大限制处分割字符串-1次,并且在第三次分割之后剩下的内容将附加在最后一个字符串结果数组元素的末尾。
  • 如果limit限制为负值,则将在不超过限制的情况下尽可能多地拆分字符串,但是会在结果中添加尾随空格(如果有的话)。实际的负值将不被考虑。
  • 如果limit限制等于0,则将在不超过限制的情况下拆分字符串。

 

1.以简单字符分割:

String wordsForSplitting = "test-splitting-string";
String[] arrayOfWords = wordsForSplitting.split("-"); // would have the same result if wordsForSplitting.split("-", 0) is used
 
System.out.println(arrayOfWords[0]);
System.out.println(arrayOfWords[1]);
System.out.println(arrayOfWords[2]);
输出:
test
splitting
string


 2.使用正则表达式拆分:

String sentenceManyDelimiters = "Split sentence when you have : , questions marks ? or email @.";
    String[] arrayOfWords = sentenceManyDelimiters.split("[,?.@:]+");
        
for (String word : arrayOfWords) {
System.out.println(word);
}
输出:
Split
sentence
when
you
have
questions
marks
or
email

3.以正数limit限制分割:

String wordsForSplitting = "test-splitting-string--";
String[] arrayOfWords = wordsForSplitting.split("-", 2);
 
for (String word : arrayOfWords) {
    System.out.println(word);
    }
输出:
test
splitting-string--

 

4.以负数限制分割:
String wordsForSplitting = "test-splitting-string--";
String[] arrayOfWords = wordsForSplitting.split("-", -15);
for (String word : arrayOfWords) {
    System.out.println(word);
    }
输出:

test
splitting
string
""
""
""

 
5.使用Stream API拆分
String sentanceCommas = "Split sentence when you have, commas, and more ..";    
List<String> stringList = Stream.of(sentanceCommas.split(","))
.map (elem -> new String(elem))
    .collect(Collectors.toList());
 
for (String obj : stringList) {
System.out.println(obj);
}
输出:
Split sentence when you have
commas
and more...