Home > Java > javaTutorial > An interesting phenomenon in java using split to split strings

An interesting phenomenon in java using split to split strings

高洛峰
Release: 2017-01-18 16:19:08
Original
1385 people have browsed it

下面有段代码:

String str="1#2#3";
String[] strs=str.split("#");
System.out.println(strs.length);
Copy after login

ok,上面这段代码最终输出结果是2,这没有问题,但是如果换成下面的写法呢,请看:

String str="##";
String[] strs=str.split("#");
System.out.println(strs.length);
Copy after login

结果输出是0,如果再换一种写法呢,请看:

String str="1##";
String[] strs=str.split("#");
System.out.println(strs.length);
Copy after login

结果输出是1,那么好了,如果我无论哪种情况都只想要2怎么办,我写了这样一段转换的代码:

String str="##";
str=str.replaceAll("#", "v^#v^");
String[] strs=str.split("#");
for (int i = 0; i < strs.length; i++) {
  String text=strs[i].replaceAll("v\\^", "");
  if("".equals(text)){
    text="略";
  }
System.out.println(text);
}
Copy after login

结果: 

An interesting phenomenon in java using split to split strings

总结

好了,问题完美解决。以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

更多An interesting phenomenon in java using split to split strings相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template