string的split问题,没分了求救!

dongfeng0803 2012-07-10 05:35:27
请教我用如下代码来分割文本时
		while(in.hasNextLine()){
String text = in.next();
String[] field = text.split(",");
System.out.println(field.length);
}

文本如下(每行都是用5个“,”分开的字段,可以为空):
201109290140,507842208552,,,,
201109290104,507842330578,腾讯,,休闲娱乐\游戏\家园,
201109290227,490012727652,手机阅读,手机阅读,休闲娱乐\小说\手机阅读,

为什么第一个的field.length为2,第二、三个为5呢?我要提取第4个的字段该怎么做?
...全文
232 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
地雷 2012-07-16
  • 打赏
  • 举报
回复
用commons下面的StringUtils里面的字符串分割方法可以实现保留空值。
比如splitByWholeSeparatorPreserveAllTokens

StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null) = ["ab", "", "", "de", "fg"]

可以参考下面的api
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#split(java.lang.String)
朱超ZhuChao.Tech 2012-07-16
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]
换个其它的方水法吧:
比如guava


Java code


String s = "201109290140,507842208552,,,,";
Iterator<String> it = Splitter.on(",").split(s).iterator();
while (it.hasNext()) {
……
[/Quote]

+1
swoky 2012-07-16
  • 打赏
  • 举报
回复
换个其它的方水法吧:
比如guava


String s = "201109290140,507842208552,,,,";
Iterator<String> it = Splitter.on(",").split(s).iterator();
while (it.hasNext()) {
System.out.println("hah:" + it.next());
}
JAKCXPP 2012-07-16
  • 打赏
  • 举报
回复
2楼正解
coooliang 2012-07-16
  • 打赏
  • 举报
回复
没用过guava,学习了!
newbie_Lee 2012-07-13
  • 打赏
  • 举报
回复
查阅API:
Splits this string around matches of the given regular expression.
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.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }
  • 打赏
  • 举报
回复
因为分割后,java中会从后面开始检查所得的数组,把空的去掉,返回非空的

23,407

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧