码迷,mamicode.com
首页 > 编程语言 > 详细

Java: String.split(....); 结果很意外

时间:2015-06-17 15:03:18      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

String txt = "join|公共聊天室||";

String[] paras = txt.splite("\\|");

String t1 = paras[0];

String t2 = paras[1];

String t3 = paras[2];

........
java.lang.ArrayIndexOutOfBoundsException: 2
 at sm.service.Service.run(Service.java:125)

程序运行中抛出这么一个错误。

 

String[] items = txt.splite("\\|"); //是这样转换成数组的,怎么数组的长度 = 2

查看了API文档,测试了一下:

String txt = "a|b|c|d||||||";
String[] msgs = txt.split("\\|",-1);
System.out.println(msgs.length);   // 输出 10

----------------------------------------------------------------------

String txt = "a|b|c|d||||||";
String[] msgs = txt.split("\\|");
System.out.println(msgs.length); //输出  4

----------------------------------------------------------------------

String txt = "a|b|c|d||||||";
String[] msgs = txt.split("\\|",0);
System.out.println(msgs.length); //输出 4

----------------------------------------------------------------------

String txt = "a|b|c|d||||||";
String[] msgs = txt.split("\\|",2);
System.out.println(msgs.length); //输出 2

----------------------------------------------------------------------

API相关资料

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

根据匹配给定的正则表达式来拆分此字符串。

此方法返回的数组包含此字符串的每个子字符串,这些子字符串由另一个匹配给定的表达式的子字符串终止或由字符串结束来终止。数组中的子字符串按它们在此字符串中的顺序排列。如果表达式不匹配输入的任何部分,则结果数组只具有一个元素,即此字符串。

limit 参数控制模式应用的次数,因此影响结果数组的长度。如果该限制 n 大于 0,则模式将被最多应用 n - 1 次,数组的长度将不会大于 n,而且数组的最后项将包含超出最后匹配的定界符的所有输入。如果 n 为非正,则模式将被应用尽可能多的次数,而且数组可以是任意长度。如果 n 为零,则模式将被应用尽可能多的次数,数组可有任何长度,并且结尾空字符串将被丢弃。

例如,字符串 "boo:and:foo" 使用这些参数可生成下列结果:

RegexLimit结果:2{ "boo", "and:foo" }:5{ "boo", "and", "foo" }:-2{ "boo", "and", "foo" }o5{ "b", "", ":and:f", "", "" }o-2{ "b", "", ":and:f", "", "" }o0{ "b", "", ":and:f" }

这种形式的方法调用 str.split(regex, n) 产生与以下表达式完全相同的结果:

Pattern.compile(regex).split(str, n)

 

 

 

 

 

 

 

参数:
regex - 定界正则表达式
limit - 结果阈值,如上所述

返回:字符串数组,根据给定正则表达式的匹配来拆分此字符串,从而生成此数组

 

-----------------------------------------------------------------------------------------------------------------

splitpublic String[] split(String regex)

根据给定的正则表达式的匹配来拆分此字符串。

该方法的作用就像是使用给定的表达式和限制参数 0 来调用两参数 split 方法。因此,结果数组中不包括结尾空字符串。

例如,字符串 "boo:and:foo" 产生带有下面这些表达式的结果:

Regex结果:{ "boo", "and", "foo" }o{ "b", "", ":and:f" }

 

 

 

 

参数:
regex - 定界正则表达式
返回:
字符串数组,根据给定正则表达式的匹配来拆分此字符串,从而生成此数组。

Java: String.split(....); 结果很意外

标签:

原文地址:http://www.cnblogs.com/personnel/p/4583113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!