简体   繁体   English

String.split()是否有可能在结果数组中返回空节点?

[英]Is it possible for String.split() to return a null node in the resulting array?

Is there any string out there that could return an array with a null node when .split is called? 是否有任何字符串可以在调用.split时返回带有空节点的数组? Here's what I tried: 这是我尝试过的:

    String string = "test,,test";
    if (string != null && !string.isEmpty()) {
        String[] parsedString = string.split(",");
        for (String stringNode : parsedString) {
            if (stringNode != null) {
                //perform logic here. Omitted for the purpose of this question.
            }
        }
    }

I want my method to be able handle a null string, but if String.split() can't return an array with a null node, then it is probably safe to remove right? 我希望我的方法能够处理空字符串,但是如果String.split()无法返回具有空节点的数组,那么删除权可能是安全的吗?

No, String.split(String regex) can never return an array with a null element in it. 不,String.split(String regex)永远不能返回其中包含null元素的数组。

There are only three cases to account for: 只有三种情况需要考虑:

  1. regex is invalid, a PatternSyntaxException is thrown regex无效,将引发PatternSyntaxException
  2. regex isn't found, the array will only contain the original string. 找不到regex ,该数组将仅包含原始字符串。
  3. regex is found, the string is split. 找到regex ,将字符串拆分。

Look at StringUtils 看看StringUtils

split( ) method. split()方法。

String str = "1,2,3,,4";
    System.out.println(Arrays.toString(str.split(",")));
    System.out.println(Arrays.toString(StringUtils.split(str,",")));

output: 输出:

[1, 2, 3, , 4]
[1, 2, 3, 4]

Is this what you expect? 这是您所期望的吗?

Hope this helps... 希望这可以帮助...

Yes, you can remove if (stringNode != null) . 是的,您可以删除if (stringNode != null) A null value will not be returned. 空值将不会返回。 An empty string might be returned by String.split() (as an array element, I mean). String.split()可能会返回一个空字符串(作为数组元素,我是说)。

根据Javadoc ,String.split()不会返回null或空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM