gpt4 book ai didi

java - 为什么这段代码不尊重我最后的分割模式

转载 作者:行者123 更新时间:2023-12-03 05:04:05 25 4
gpt4 key购买 nike

首先,这是我的代码:

String line = "Events|1005435529|7021370073||PAGELOAD|2017-06-19T12:04:40||JI||ServerHostName|ServerIPAddress|9P2_D2jB9Toct7PDTJ7zwLUmWfEYz6Y4akyOKn2g4CepveMH4wr3!46548593!1497854077121|||||||||||";
int offset = line.indexOf("Events");
String zeroIn = line.substring(offset);
String[] jsonElements = zeroIn.split("\\|");
System.out.println(Arrays.asList(jsonElements));

输出:

[Events, 1005435529, 7021370073, , PAGELOAD, 2017-06-19T12:04:40, , JI, , ServerHostName, ServerIPAddress, 9P2_D2jB9Toct7PDTJ7zwLUmWfEYz6Y4akyOKn2g4CepveMH4wr3!46548593!1497854077121]`

我还注意到每个数组元素在开头添加了空格。

我的问题是,我在字符串 line 的末尾有近 10 个空管道符号,而由于空管道符号的第一次出现、第二次出现和第三次出现受到尊重,所以最后一个符号被遗漏并且不存在不在数组中相加。我在这里想念什么?

最佳答案

split(java.lang.String regex)来电 split(java.lang.String regex ,int limit)参数为 0。

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.

您可以自己使用正值(并且足够大以确保包含所有 token )调用此方法,以防止丢弃空 token :

String[] jsonElements = zeroIn.split("\\|", zeroIn.length());

注意:从下面的评论来看,使用负值确实是更好的方法:

String[] jsonElements = zeroIn.split("\\|", -1);

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

关于java - 为什么这段代码不尊重我最后的分割模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44626823/

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