Java 将字符串拆分为数组

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

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

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

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

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

我的值只保存到最后一个0。“ | | |”部分似乎被删除了。 我做错了什么?

谢谢

479656 次浏览

This is expected. Refer to Javadocs for split.

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

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

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.

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);

Try this

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

Consider this example:

public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println
(java.util.Arrays.toString(testString.split("\\|")));
// output : [Real, How, To]
}
}

The result does not include the empty strings between the "|" separator. To keep the empty strings :

public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println
(java.util.Arrays.toString(testString.split("\\|", -1)));
// output : [Real, How, To, , , ]
}
}

For more details go to this website: http://www.rgagnon.com/javadetails/java-0438.html