string.indexとstring.lengthを使用して文字列を分割しようとしましたが、文字列が範囲外であるというエラーが表示されます。どうすれば修正できますか?最初のスペースから文字列を分割する方法Java
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.indexとstring.lengthを使用して文字列を分割しようとしましたが、文字列が範囲外であるというエラーが表示されます。どうすれば修正できますか?最初のスペースから文字列を分割する方法Java
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
は、この周りにいくつかでなければなりません。
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
リミットでの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);
うまくいった!明らかにそれは限界と関係していた! –
string.split(" ",2)
分割は、パターンが適用される回数を制限する制限入力をとります。
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
は決して '」「' 'temp'で、そのケースを扱うが存在しない場合に何が起こるかを考えてみましょう。 – Zircon
'' ''は32のASCII値を持っているので' '' + temp.length() - 1'は32より大きくなり、' temp.length() 'が32より大きくなるのを疑う。 '' ''の代わりに' 'temp.indexOf(' ')'を使い、 'temp.length() - 1'を追加しないでください。 –