gpt4 book ai didi

java - Java中如何用null分割字符串直到结尾?

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

我必须对一个简单的 Double 数组进行字符串化才能将其放入我的数据库中(在本例中,这是我发现的最佳方法)

我正在使用 StringUtils.join() 进行字符串化,但我遇到了分割问题,因为数组末尾有很多空值(这是预期的)。

这是一些代码示例:

final String NEEDLE = "_";
Double[] dblArray = new Double[]{2.0, 2.0, 2.0, 0.0, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null};
String joined = StringUtils.join(dblArray, NEEDLE);
String[] split = joined.split(NEEDLE); //I will then cast the string to double

Log.d("MyApp", "joined=" + joined);
Log.d("MyApp", "1 - split=" + Arrays.toString(split));
Log.d("MyApp", "2 - StringUtils.split=" + Arrays.toString(StringUtils.split(joined, NEEDLE)));
Log.d("MyApp", "3 - split+xxx=" + Arrays.toString((joined+"xxx").split(NEEDLE)));
Log.d("MyApp", "4 - StringUtils.split+xxx=" + Arrays.toString(StringUtils.split(joined+"xxx", NEEDLE)));

结果如下:

D: joined=2.0_2.0_2.0_0.0_______________________________________________________
D: 1 - split=[2.0, 2.0, 2.0, 0.0]
D: 2 - StringUtils.split=[2.0, 2.0, 2.0, 0.0]
D: 3 - split+xxx=[2.0, 2.0, 2.0, 0.0, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , xxx]
D: 4 - StringUtils.split+xxx=[2.0, 2.0, 2.0, 0.0, xxx]

预期的行为是#3,但正如您所看到的,为了让我的拆分结果包含空值,我必须在字符串末尾添加一些内容,这是非常意外的。

是否有一种干净的方法可以将其与空值分开直到最后,但最后不添加虚拟值?

最佳答案

您正在调用 split(NEEDLE) :

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.

您应该调用split(NEEDLE, -1) :

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.

关于java - Java中如何用null分割字符串直到结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44994884/

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