2016-09-27 9 views
5

string.indexとstring.lengthを使用して文字列を分割しようとしましたが、文字列が範囲外であるというエラーが表示されます。どうすれば修正できますか?最初のスペースから文字列を分割する方法Java

String nickname = temp.substring(0, temp.indexOf(' ')); 
String content = temp.substring(temp.indexOf(' ') + 1); 
+1

は決して '」「' 'temp'で、そのケースを扱うが存在しない場合に何が起こるかを考えてみましょう。 – Zircon

+0

'' ''は32のASCII値を持っているので' '' + temp.length() - 1'は32より大きくなり、' temp.length() 'が32より大きくなるのを疑う。 '' ''の代わりに' 'temp.indexOf(' ')'を使い、 'temp.length() - 1'を追加しないでください。 –

答えて

0

は、この周りにいくつかでなければなりません。

String foo = "some string with spaces"; 
String parts[] = foo.split(" ", 2); 
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1])); 

あなたが取得します:

cr: some, cdr: string with spaces 
9

リミットでのjava.lang.String split関数を使用します。

while (in.hasNextLine()) { 

      String temp = in.nextLine().replaceAll("[<>]", ""); 
      temp.trim(); 

      String nickname = temp.substring(temp.indexOf(' ')); 
      String content = temp.substring(' ' + temp.length()-1); 

      System.out.println(content); 
+0

うまくいった!明らかにそれは限界と関係していた! –

関連する問題