Java将字符串拆分为数组

编程入门 行业动态 更新时间:2024-10-12 14:20:44
本文介绍了Java将字符串拆分为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I need help with the split() method. I have the followingString:

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

我需要将值放入数组中。有3种可能的字符串:0,1和

I need to put the values into an array. There are 3 possible strings: "0", "1", and ""

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

My problem is, when i try to use split():

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

我的值仅保存到最后0.看起来像|||部分被修剪。 我做错了什么?

My values are saved only until the last 0. Seems like the part "|||" gets trimmed. What am i doing wrong?

谢谢

推荐答案

String.split(String regex) (强调我的):

This behavior is explicitly documented in String.split(String regex) (emphasis mine):

此方法的作用就像通过调用给定表达式和limit参数为零的双参数split方法一样。因此,尾随空字符串在结果数组中不包含。

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

If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):

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

更多推荐

Java将字符串拆分为数组

本文发布于:2023-11-29 22:33:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647818.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!