Java String.split() 关于空值(empty results)

  • Post author:
  • Post category:java


现象

String testString1 = "1, 1, 0, 0, 0, 6.17, 3.50,,,,,,,,,,,,,1";
String testString2 = "1, 1, 0, 0, 0, 6.17, 3.50,,,,,,,,,,,,,";

采用默认的split方式

testString.split(",");

这两者的结果是不一致的,前者的长度是20,后者为7. 因为字符串中产生了空值。如果头和尾都有值,中间空,长度不影响。否则split结果会去掉空值。

细看下split的API

public String[] split(String regex,

int limit)

Splits this string around matches of the given

regular expression.


The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is

greater than zero

then the pattern will be applied

at most n – 1 times

, the array’s length will be no greater than n, and the array’s last entry will contain all input beyond the last matched delimiter. If

n is non-positive

then the pattern will be applied

as many times as possible

and the array can have any length. If

n is zero

then the pattern will be applied

as many times as possible

, the array can have any length, and trailing empty strings will be discarded.

从API来看,核心有两点

  1. 第一个参数是正则表达式
  2. 第二个limit参数指定分割结果数目

解决方案

保留所有空值

String[] tpStrings = testString.split(",",-1);

不管空值出现在哪里,都不会丢弃

去掉空值

String[] tpStrings = testString.split(",+");

就是中间出现空值,也会舍弃



版权声明:本文为Crystal_Zero原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。