如何拆分仅包含定界符的字符串? [英] How can split a string which contains only delimiter?

查看:37
本文介绍了如何拆分仅包含定界符的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码:

String sample = "::";
String[] splitTime = sample.split(":");
// extra detail omitted
System.out.println("Value 1 :"+splitTime[0]);
System.out.println("Value 2 :"+splitTime[1]);
System.out.println("Value 3 :"+splitTime[2]);

我遇到了 ArrayIndexOutofBound 异常. String.split()如何处理连续的或尾随的/分隔符?

I am getting ArrayIndexOutofBound exception. How does String.split() handle consecutive or trailing / opening delimiters?

另请参见:

推荐答案

Alnitak是正确的,默认情况下会丢弃尾随的空字符串.

Alnitak is correct that trailing empty strings will be discarded by default.

如果要使用结尾的空字符串,则应使用

If you want to have trailing empty strings, you should use split(String, int) and pass a negative number as the limit parameter.

limit 参数控制模式被应用,因此影响结果的长度大批.如果限制 n 大于零,则该模式将最多应用 n  -  1次,该数组的长度将不大于 n ,并且该数组的最后一个条目将包含除最后一个匹配的定界符之外的所有输入.如果 n 如果为非正数,则该模式将被应用多次可能并且数组可以有任何长度.如果 n 为零,则该模式将被尽可能多地应用,该数组可以有任何长度,尾随的空字符串将被丢弃.

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.

请注意 split(aString) split(aString,0):

此方法的工作方式就像通过调用带有给定表达式且限制参数为零的两个参数 split 方法一样.因此,结尾的空字符串不包括在结果数组中.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

此外,您应该使用循环从数组中获取值.这样可以避免 ArrayIndexOutOfBoundsException .

Also, you should use a loop to get the values from the array; this avoids a possible ArrayIndexOutOfBoundsException.

因此您的更正代码应该是(假设您想要尾随空字符串):

So your corrected code should be (assuming you want the trailing empty strings):

String sample = "::";
String[] splitTime = sample.split(":", -1);
for (int i = 0; i < splitTime.length; i++) {
    System.out.println("Value " + i + " : \"" + splitTime[i] + "\"");
}

输出:


Value 0 : ""
Value 1 : ""
Value 2 : ""

这篇关于如何拆分仅包含定界符的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆