可能重复:
如何通过空格分割字符串
我需要在解析文本文件时帮助。 文本文件包含类似下面的数据:
This is different type of file.
Can not split it using ' '(white space)
我的问题是单词之间的空格不一致。有时只有一个空格,有时会出现多个空格。
我需要将字符串拆分,以便获得单词而不是空格。
可能重复:
如何通过空格分割字符串
我需要在解析文本文件时帮助。 文本文件包含类似下面的数据:
This is different type of file.
Can not split it using ' '(white space)
我的问题是单词之间的空格不一致。有时只有一个空格,有时会出现多个空格。
我需要将字符串拆分,以便获得单词而不是空格。
str.split("\\s+")
可以起到作用。正则表达式末尾的 +
,将多个空格视为单个空格处理。它返回一个没有任何 " "
结果的字符串数组 (String[]
)。
量词
来指定您想要拆分的空格数量:- `+` - Represents 1 or more
`*` - Represents 0 or more
`?` - Represents 0 or 1
`{n,m}` - Represents n to m
因此,\\s+
将会在 一个或多个
空格处拆分您的字符串
String[] words = yourString.split("\\s+");
{}
之间给出您的范围:yourString.split("\\s{3,6}"); // Split String on 3 to 6 spaces
使用正则表达式。
String[] words = str.split("\\s+");
您可以使用正则表达式模式
public static void main(String[] args)
{
String s="This is different type of file.";
String s1[]=s.split("[ ]+");
for(int i=0;i<s1.length;i++)
{
System.out.println(s1[i]);
}
}
输出
This
is
different
type
of
file.
\t\n\x0B\f\r
)拆分。请改用字符类\s
(任何空白字符),正如其他人所描述的那样。 String[] words = yourString.split("\\s+");
- jlordoString spliter="\\s+";
String[] temp;
temp=mystring.split(spliter);
如果你不想使用分割方法,我可以给你另一种将字符串进行标记化的方法。以下是该方法:
public static void main(String args[]) throws Exception
{
String str="This is different type of file.Can not split it using ' '(white space)";
StringTokenizer st = new StringTokenizer(str, " ");
while(st.hasMoreElements())
System.out.println(st.nextToken());
}
}
你可以使用 String 类的 replaceAll(String regex, String replacement) 方法将多个空格替换为一个空格,然后再使用 split 方法。