テキストファイルを解析しながら、私は助けを必要としています。 テキストファイルには、私の問題は、単語の間にスペースが似ていないです
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[]
)を返します。
正規表現を使用してください。あなたが上で分割したいスペースの数を指定するQuantifiers
を使用することができます
String[] words = str.split("\\s+");
: - だから、
`+` - 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
あなたは、スペースで複数のスペースを置き換えるために
でReplaceAll(文字列の正規表現、文字列置換)Stringクラスのメソッドを使用することができ、その後、あなたは、分割方法を使用することができます。
あなたは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.
あなたのソリューションは空白で分割され、 '\ t \ n \ x0B \ f \ r'のような他の空白文字では分割されません。代わりに文字クラス '\ s'(任意の空白文字)を使用してください。 'String [] words = yourString.split(" \\ s + "); ' – jlordo
String 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());
}
}
なぜ、' StringTokenizer'よりも良い方法だとすれば、splitメソッドを使いたいのではないでしょうか? 'StringTokenizer'の使用を中止してください。 –
RohitはStringTokenizerよりもsplitが優れている理由を説明することができます –
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 –
Thanx for help ... –
@SachinMhetre:どうぞよろしくお願いいたします。 :) –