Java 拆分 - 长度错误
Java Split - wrong length
为什么我收到的长度是 3 而不是 4?我怎样才能解决这个问题以提供适当的长度?
String s="+9851452;;FERRARI;;";
String split[]=s.split("[;]");
System.out.println(split.length);
您收到的长度为 3,因为 split
、
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 s="+9851452;;FERRARI;;";
String split[]=s.split(";", -1);
System.out.println(Arrays.toString(split));
您只需要忽略或删除第 5 项,或删除尾随的 ;
- 它显示是因为在 4 个标记的两侧有 5 个(可能是空白的)字符串。有关详细信息,请参阅 docs。
String split[]=s.split("[;]", -1);
为什么它不起作用的答案在文档中:http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split%28java.lang.String%29。 "Trailing empty strings are therefore not included in the resulting array.".
您可以使用 apache commons lang 中的 StringUtils。
String s="+9851452;;FERRARI;;";
Arrays.toString(StringUtils.splitPreserveAllTokens(s, ";"))
为什么我收到的长度是 3 而不是 4?我怎样才能解决这个问题以提供适当的长度?
String s="+9851452;;FERRARI;;";
String split[]=s.split("[;]");
System.out.println(split.length);
您收到的长度为 3,因为 split
、
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 s="+9851452;;FERRARI;;";
String split[]=s.split(";", -1);
System.out.println(Arrays.toString(split));
您只需要忽略或删除第 5 项,或删除尾随的 ;
- 它显示是因为在 4 个标记的两侧有 5 个(可能是空白的)字符串。有关详细信息,请参阅 docs。
String split[]=s.split("[;]", -1);
为什么它不起作用的答案在文档中:http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split%28java.lang.String%29。 "Trailing empty strings are therefore not included in the resulting array.".
您可以使用 apache commons lang 中的 StringUtils。
String s="+9851452;;FERRARI;;";
Arrays.toString(StringUtils.splitPreserveAllTokens(s, ";"))