不确定在这种情况下字符串分割实际上是如何工作的
我没有得到以下内容:
在以下 String
中:
String s = "1234;x;;y;";
如果我这样做:String[] s2 = s.split(";");
我得到 s2.length
为 4,
s2[0] = "1234";
s2[1] = "x";
s2[2] = "";
s2[3] = "y";
但在字符串中: String s = "1234 ;x;y;;";
我得到:
s2.length
为 3 并且
s2[0] = "1234";
s2[1] = "x";
s2[2] = "y";
?
有什么区别,在后一种情况下我也没有得到 4 吗?
更新:
使用 -1
并不是我所期望的行为。
我的意思是最后一个分号是 String
的结尾,所以在后一个示例中我也期望 4
作为数组的长度
I don't get the following:
In the following String
:
String s = "1234;x;;y;";
if I do:String[] s2 = s.split(";");
I get s2.length
to be 4 and
s2[0] = "1234";
s2[1] = "x";
s2[2] = "";
s2[3] = "y";
But in the string: String s = "1234;x;y;;";
I get:
s2.length
to be 3 and
s2[0] = "1234";
s2[1] = "x";
s2[2] = "y";
?
What is the difference and I don't get 4 in the latter case as well?
UPDATE:
Using -1
is not was I was expecting as behavior.
I mean the last semicolon is the end of the String
so in the latter example I was also expecting 4
as length of the array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
来自 文档,
更新:
您有五个由
分隔的子字符串;
在第二种情况下,它们是1234
、x
、y
、和
。根据文档,分割操作产生的所有空子字符串(最后)都将被消除。
有关详细信息,请参阅 这里。
例如,字符串
boo:and:foo
使用这些参数会产生以下结果:From the docs,
UPDATE:
You have five substrings separated by
;
In the second case, these are1234
,x
,y
,and
. As per the docs, all empty substrings (at the end) which result from the split operation would be eliminated.
For details, look here.
The string
boo:and:foo
, for example, yields the following results with these parameters:省略尾随的空字符串。然而,如果需要的话,有一些方法可以显式地包含它们。
Trailing empty strings are omitted. However, there are ways to include them explicitly, if needed.
来自 http:// docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)
From http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)
好问题。如果您检查 String.split() 的 API 文档 并使用“boo:foo”检查示例,然后您可以看到尾随的空字符串被省略。
Good question. If you check the API documentation for
String.split()
and check the example with "boo:foo" then you can see that the trailing empty strings are omitted.这是 java 中 split 方法的默认行为,不返回空标记。 ]
s.split("\;", -1);应该返回空令牌
Thats default behavior of split method in java to not return empty tokens . ]
s.split("\;", -1); should return empty token
为什么不先检查文档说了什么。这是链接:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29
这是您的答案:
Why not check what does the documention says first. Here is the link:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29
And here is your answer: