我在解析文本文件时需要帮助。文本文件包含数据,例如
This is different type of file.
Can not split it using ' '(white space)
我的问题是单词之间的空格不相似。有时只有一个空格,有时会给出多个空格。
我需要以只得到单词而不是空格的方式分割字符串。
str.split("\\s+")
将起作用。正则表达式末尾的+
将把多个空格视为单个空格。它返回没有任何String[]
结果的字符串数组(" "
)。
您可以使用Quantifiers
指定要分割的空格数:-
您可以使用正则表达式模式
使用正则表达式。
您可以使用String类的replaceAll(String regex,String replace)方法用空格替换多个空格,然后可以使用split方法。
String[] words = str.split("\\s+");
如果您不想使用split方法,我给您另一种方法来给您的字符串添加字符串。这里是方法