在Java [重复]中的多个空格上分割字符串

问题描述 投票:22回答:7

可能重复:How to split a String by space

我在解析文本文件时需要帮助。文本文件包含数据,例如

This is     different type   of file.
Can not split  it    using ' '(white space)

我的问题是单词之间的空格不相似。有时只有一个空格,有时会给出多个空格。

我需要以只得到单词而不是空格的方式分割字符串。

java string split
7个回答
46
投票

str.split("\\s+")将起作用。正则表达式末尾的+将把多个空格视为单个空格。它返回没有任何String[]结果的字符串数组(" ")。


16
投票

您可以使用Quantifiers指定要分割的空格数:-


5
投票

您可以使用正则表达式模式


4
投票

使用正则表达式。


0
投票

您可以使用String类的replaceAll(String regex,String replace)方法用空格替换多个空格,然后可以使用split方法。


0
投票
String[] words = str.split("\\s+");

0
投票

如果您不想使用split方法,我给您另一种方法来给您的字符串添加字符串。这里是方法

© www.soinside.com 2019 - 2024. All rights reserved.