本文介绍了java - 如果字符串后跟两个或多个空格/空格,如何拆分字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的字符串中,我想根据两个或多个空格拆分字符串或标记字符串.
In my string, i want to split the string or tokenize string on the basis of two or more spaces.
例如
string = "I am Chaitanya Gadam. Split this srting."
我希望输出为 -
str[0]= "I am"
str[1]= "Chaitanya Gadam."
str[2]= "Split"
str[3]= "this string."
推荐答案
string.split("\\s\\s+");
(或)
string.split("\\s{2,}");
String string = "I am Chaitanya Gadam. Split this srting.";
String[] str = string.split("\\s{2,}");
for(String s: str)
{
System.out.println(s+":"+s.length());
}
System.out.println(Arrays.toString(string.split("\\s\\s+")));
Output:
I am:4
Chaitanya Gadam.:16
Split:5
this srting.:12
[I am, Chaitanya Gadam., Split, this srting.]
用两个或多个空格作为分隔符分割字符串.在 Regex 中使用转义字符可以提高可读性,而不是使用空格字符.
Splits strings with two or more spaces as delimiter. Using Escape character in the Regex increases readability instead of using space character.
这篇关于java - 如果字符串后跟两个或多个空格/空格,如何拆分字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!