2016-09-27 46 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

工作也很好!!显然它必须做的极限! –