gpt4 book ai didi

java string.split() 问题

转载 作者:行者123 更新时间:2023-12-01 08:01:27 25 4
gpt4 key购买 nike

在解决UVa question时,我得到了这个 String ,我需要将其拆分为 String 数组,删除 #@

巴西#2@1#苏格兰

我在使用时遇到 ArrayOutOfBounds 异常,

matchSummary.split("#@");

在研究了这个 UVa 问题的解决方案后,我发现其他经验丰富的竞争程序员已经这样做了,

string.split("[#@]");

并通过了在线评委的裁决。

我无法为上述String分割这个String

我对这个问题的完整解决方案可以在这里找到 - see

任何人都可以向我解释为什么我的代码可以使用 split("[#@]"); 吗?

最佳答案

Java regular expressions ,方括号内的字符 []称为字符类。

这个...

String input = "Brazil#2@1#Scotland";
System.out.println(Arrays.toString(input.split("[#@]")));

...将分割 String带有任一分隔符 #@ ,无论顺序如何,输出:

[Brazil, 2, 1, Scotland]

在这种情况下相当于:

System.out.println(Arrays.toString(input.split("#|@")));

但是,与 #@ 分开未包含在 [] 中将搜索 # 的序列接下来是 @

这不会触发任何 ArrayIndexOutOfBoundsException本身,它只会返回 1 大小的 array包含原始输入String

但是,您可能假设 array大小为> 1稍后在代码中,因此 Exception

关于java string.split() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25024086/

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