gpt4 book ai didi

java - 如何拆分仅包含定界符的字符串?

转载 作者:太空狗 更新时间:2023-10-29 22:44:12 24 4
gpt4 key购买 nike

我正在使用以下代码:

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() 如何处理连续或尾随/开始的定界符?

另见:

最佳答案

Alnitak 是正确的,默认情况下尾随的空字符串将被丢弃。

如果你想要尾随空字符串,你应该使用split(String, int)并传递一个负数作为 limit 参数。

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) 的同义词:

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

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

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 : ""

关于java - 如何拆分仅包含定界符的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/785586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com