Java:当单词之间有可变数量的空格时,按空格分割字符串? [英] Java: Splitting a string by whitespace when there is a variable number of whitespaces between words?

查看:308
本文介绍了Java:当单词之间有可变数量的空格时,按空格分割字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

String string = "1-50  of 500+";
String[] stringArray = string.split(" ");

打印出这个数组中的所有元素给出了以下内容:

Printing out all the elements in this array gives me the following:

Element 1: 1-50
Element 2:  of 500+

如何通过要求单词之间至少有一个空格来分割元素?

How can I get it to split elements by the requirement that there is at least one whitespace between the words?

其他单词,我希望我的元素是:

In other words, I want my elements to be:

Element 1: 1-50
Element 2: of
Element 3: 500+


推荐答案

使用 \\\\ + 即使它们更多,也要拆分空格。

Use \\s+ to split on spaces even if they are more.

String string = "1-50  of 500+";
String[] stringArray = string.split("\\s+");

for (String str : stringArray)
{
    System.out.println(str);
}

完整示例: http://ideone.com/CFVr6N

编辑:

如果您还要拆分选项卡,请将正则表达式更改为 \\\\ + | \\t + 并且它还检测空格和制表符。

If you also want to split on tabs, change the regex to \\s+|\\t+ and it detects both spaces and tabs as well.

这篇关于Java:当单词之间有可变数量的空格时,按空格分割字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆