2016-09-27 35 views
5

我試圖使用string.index和string.length拆分字符串,但我得到一個錯誤,該字符串超出範圍。我該如何解決這個問題?如何從第一個空間發生的字符串拆分Java

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); 
+1

試想,如果沒有'」「'在'temp',然後處理這種情況會發生什麼。 – Zircon

+0

''''具有32位的ASCII值,所以'''+ temp.length() - 1'將大於32,並且我懷疑'temp.length()'大於32.你需要使用'temp.indexOf('')'而不是''''並且不要添加'temp.length() - 1'。 –

回答

0

必須有一些解決此問題:

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

使用java.lang.String中有限制分裂功能。

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

工作也很好!!顯然它必須做的極限! –