return nameString.substring(nameString.indexOf(" ", 0), nameString.lastIndexOf(" ", 0));
为什么一直返回错误?我只想将字符串从第一个出现的空格字符返回到字符串中最后一个出现的空格?
最佳答案
lastIndexOf
public int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index... If no such value exists, then -1 is returned.
去掉 indexOf 和 lastIndexOf 的 , 0
参数。当您将 0 的 fromIndex 传递给 lastIndexOf 时,它会从字符串的开头搜索 backwards 以找到匹配项。如果找不到,则返回 -1,这是子字符串的无效参数。
return nameString.substring(nameString.indexOf(" "), nameString.lastIndexOf(" "));
关于java - 为什么我总是让 String 超出范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7734817/