gpt4 book ai didi

Java将字符串拆分为数组

转载 作者:IT老高 更新时间:2023-10-28 11:36:46 25 4
gpt4 key购买 nike

我需要 split() 方法的帮助。我有以下String:

String values = "0|0|0|1|||0|1|0|||";

我需要将这些值放入一个数组中。有 3 个可能的字符串:“0”、“1”和“”

我的问题是,当我尝试使用 split():

String[] array = values.split("\\|"); 

我的值只保存到最后一个 0。看起来像部分“|||”被修剪。我做错了什么?

谢谢

最佳答案

此行为在 String.split(String regex) 中有明确记录。 (强调我的):

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.

如果你想包含那些尾随的空字符串,你需要使用 String.split(String regex, int limit)第二个参数为负值(limit):

String[] array = values.split("\\|", -1);

关于Java将字符串拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14414582/

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