Java – split(regex,limit)方法实际上如何工作?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java – split(regex,limit)方法实际上如何工作?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1934字,纯文字阅读大概需要3分钟。
内容图文
![Java – split(regex,limit)方法实际上如何工作?](/upload/InfoBanner/zyjiaocheng/811/56300a9d06a545f481de1c0c1bbc8edf.jpg)
参见英文答案 > Java – String split() Method, zero and negative limit 3个
我试图理解拆分方法是如何工作的,并对它有轻微的困惑.在oracle的文档页面中给出的这个例子中,
String str = "boo:and:foo";
String[] str1 = str.split("o",2);
Output
b
o:and:foo
这很容易理解,字符串在第一个’o’的出现时实际上是分开的
但对于
String[] str1 = str.split("o",3);
Output:
b
:and:foo
这是怎么出来的?
解决方法:
我从文档中了解到:
The limit parameter controls the number of times the pattern is
applied and therefore affects the length of the resulting array. If
the limit n is greater than zero then the pattern will be applied at
most n – 1 times, the array’s length will be no greater than n, and
the array’s last entry will contain all input beyond the last matched
delimiter. If n is non-positive then the pattern will be applied as
many times as possible and the array can have any length. If n is zero
then the pattern will be applied as many times as possible, the array
can have any length, and trailing empty strings will be discarded.
这意味着在字符串s上设计或剪切到n次,因此让我们逐一分析以更好地理解:
限制1
String[] spl1 = str.split("o", 1);
这意味着将它分割或切割在字符串o上的一个字符串上,在这种情况下,您将获得所有输入:
[boo:and:foo]
1
限制2
String[] spl1 = str.split("o", 2);
这意味着在o上减少一次,所以我会在第一个o中断
boo:and:foo
-----^
在这种情况下,您将得到两个结果:
[b,o:and:foo]
1 2
限制3
String[] spl1 = str.split("o", 3);
这意味着在第一个o和第二个o上切两次
boo:and:foo
1----^^--------------2
在这种情况下,您将得到三个结果:
[b, ,:and:foo]
1 2 3
限制4
String[] spl1 = str.split("o", 4);
这意味着在第一,第二和第三o上三次削减它
boo:and:foo
1_____^^ ^
|___2 |___3
在这种情况下,您将得到四个结果:
[b, ,:and:f,o]
1 2 3 4
限制5
String[] spl1 = str.split("o", 5);
这意味着在第一,第二,第三和第四次切割它四次
boo:and:foo
1_____^^ ^^
|___2 ||___4
|____3
在这种情况下,您将获得五个结果:
[b, ,:and:f, , ]
1 2 3 4 5
只是一个简单的动画来了解更多:
内容总结
以上是互联网集市为您收集整理的Java – split(regex,limit)方法实际上如何工作?全部内容,希望文章能够帮你解决Java – split(regex,limit)方法实际上如何工作?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。