2012-10-26 29 views
5

可能性の重複:
How to split a String by space分割文字列

テキストファイルを解析しながら、私は助けを必要としています。 テキストファイルには、私の問題は、単語の間にスペースが似ていないです

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

正規表現を使用してください。あなたが上で分割したいスペースの数を指定するQuantifiersを使用することができます

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

: - だから、

`+` - 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

あなたはmethod.Hereがあるスプリットを使用したくない場合、私はあなたの文字列をtockenizeする別の方法を与えている

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

正規表現パターンを使用することができますメソッド

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

なぜ、' StringTokenizer'よりも良い方法だとすれば、splitメソッドを使いたいのではないでしょうか? 'StringTokenizer'の使用を中止してください。 –

+0

RohitはStringTokenizerよりもsplitが優れている理由を説明することができます –

+0

http://stackoverflow.com/questions/691184/scanner-vs-stringtokenizer-vs-string-split http://www.javamex.com/tutorials /regular_expressions/splitting_tokenisation_performance.shtmlおよびhttp://stackoverflow.com/questions/5965767/performance-of-stringtokenizer-class-vs-split-method-in-java –