2012-10-26 70 views
5

可能重复:
How to split a String by space分割字符串中的Java

我需要帮助,而解析的文本文件。 该文本文件包含像

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

我的问题是单词之间的空格都没有类似的数据。有时候会有单个空间,有时会有多个空间。

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

回答

16

试试看str.split("\\s+")。它返回一个字符串数组(String[])。

+0

Thanx for help ... –

+0

@SachinMhetre:不客气。 :) –

3

使用正则表达式。

String[] words = str.split("\\s+"); 
6

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

`+` - Represents 1 or more 
    `*` - Represents 0 or more 
    `?` - Represents 0 or 1 
`{n,m}` - Represents n to m 

所以,\\s+将分裂的one or more空间

String[] words = yourString.split("\\s+"); 

而且你的字符串,如果你想指定一些具体的数字,你可以给你的范围{}

yourString.split("\\s{3,6}"); // Split String on 3 to 6 spaces 
0

可以使用
的replaceAll(字符串的正则表达式,字符串替换)String类的方法来代替用空间的多个空间,然后可以使用分割法。

3

你可以使用正则表达式

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. 
+0

您的解决方案只能按空格分割,而不能由其他任何空白字符(例如'\ t \ n \ x0B \ f \ r')分割。正如其他人所描述的那样,使用字符类'\ s'(任何空格字符)。 'String [] words = yourString.split(“\\ s +”); ' – jlordo

0
String spliter="\\s+"; 
String[] temp; 
temp=mystring.split(spliter); 
0

我给你另一种方法来tockenize您的字符串,如果你不想使用分割method.Here是方法

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()); 
} 
} 
+0

为什么他不想使用split方法,因为它比StringTokenizer更好?请停止使用'StringTokenizer'。 –

+0

Rohit能说明为什么split比StringTokenizer更好 –

+0

你可以看到http://stackoverflow.com/questions/691184/scanner-vs-stringtokenizer-vs-string-split http://www.javamex.com/tutorials /regular_expressions/splitting_tokenisation_performance.shtml and http://stackoverflow.com/questions/5965767/performance-of-stringtokenizer-class-vs-split-method-in-java –