拆分字符串,保留所有尾随空元素 [英] Split strings keeping all trailing empty elements

查看:113
本文介绍了拆分字符串,保留所有尾随空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对java编程比较陌生。你如何分割由分号分隔的以下字符串?

I am relatively new to java programming. How would you split following lines of Strings separated by semicolons?

String; String; String; String, String; String;;String;
String; String; String; ;String;String;String;String

我想将每个String作为参数传递给构造函数(来自txt文件),但我无法找到可通行的正则表达式。构造函数有8个String参数(从两个分号之间没有任何内容 ;; ,我想获得一个空字符串)。在这种情况下,将创建两个单独的对象。我知道如何拆分字符串通常是有效的,但这对我来说似乎太棘手了。

I would like to pass each String as an argument into a constructor (from txt file), but I am unable to find passable regex for the purpose. The constructor has 8 String arguments (from where there is nothing between two semicolons ;;, I would like to get an empty String). In this case two separate objects would be created. I am aware of how splitting a String generally works but this one seems to be too tricky for me.

推荐答案

问题是 String.Split 不保留尾随空元素:

The issue is the String.Split does not keep the trailing empty elements:


尾随空字符串是因此不包含在结果数组中。

Trailing empty strings are therefore not included in the resulting array.

要包含它们,请使用 -1 作为第二个参数(参见演示):

To include them, use -1 as the second argument (see demo):

String s  = "String; String; String; String, String; String;;String;";
System.out.println(Arrays.toString(s.split(";", -1)));

请参阅 Java reference


public String [] split(String regex,int limit)

limit 参数控制模式的应用次数,因此影响结果数组的长度...... 如果 n 是非正数,那么模式将被应用尽可能多次,并且数组可以具有任何长度 。如果 n 为零,那么模式将被应用尽可能多次,数组可以有任何长度,尾随空字符串将被丢弃

public String[] split(String regex, int limit)
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array... 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.

这篇关于拆分字符串,保留所有尾随空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆