java 中的字符串方法子字符串错误

Error in string method substring in java

我在这段代码中遇到了这个错误。我该怎么办?

//错误

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1931)
at StringExample.main(StringExample.java:18) 

//代码

String s=sc.nextLine();
int first=s.indexOf("");
int second=s.lastIndexOf("");
String sur=s.substring(second+1);      //18 line
String middle=s.substring(first+1,second);
String firstname=s.substring(0,first);
System.out.println(sur+""+firstname+""+middle);

代码中 second 的值很可能是字符串的最后一个索引。对于 hello world,它将是 11。

现在,如果您增加该数字并将其用作字符串的第一个索引,您将得到 -1,因为您的起始索引大于字符串中的最后一个索引。

从逻辑上讲,这也说不通。您尝试从实际字符串之后开始的字符串中获取子字符串。

查看您的示例,我认为您应该改用 indexOf(" ")。它为您提供 space 的索引。

.indexOf("") 方法为您提供字符串的开头,.lastIndexOf("") 为您提供字符串的结尾。我认为您应该使用最后一个索引方法(".lastIndexOf("") ) 就像 .lastIndexOf(" ");.