Java子串:'字符串索引超出范围'
-
11-09-2019 - |
题
我猜我收到此错误是因为该字符串试图对 a 进行子串 null
价值。但岂不是 ".length() > 0"
部分消除这个问题?
这是 Java 片段:
if (itemdescription.length() > 0) {
pstmt2.setString(3, itemdescription.substring(0,38));
}
else {
pstmt2.setString(3, "_");
}
我收到这个错误:
java.lang.StringIndexOutOfBoundsException: String index out of range: 38
at java.lang.String.substring(Unknown Source)
at MASInsert2.itemimport(MASInsert2.java:192)
at MASInsert2.processRequest(MASInsert2.java:125)
at MASInsert2.doGet(MASInsert2.java:219)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:627)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:835)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:640)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1286)
at java.lang.Thread.run(Unknown Source)
解决方案
I“猜我得到这个错误 因为字符串试图 串Null值。但不会 的”。长度()> 0" 的部分消除 这个问题?
没有,调用itemdescription.length()时itemdescription为空就不会产生的StringIndexOutOfBoundsException,而是因为你一个NullPointerException将基本上试图调用一个方法的无效
正如其他人所指出的,的StringIndexOutOfBoundsException表示itemdescription不长至少38个字符。你可能要处理两个条件(我假设你要截断):
final String value;
if (itemdescription == null || itemdescription.length() <= 0) {
value = "_";
} else if (itemdescription.length() <= 38) {
value = itemdescription;
} else {
value = itemdescription.substring(0, 38);
}
pstmt2.setString(3, value);
可能是一个好地方,一个效用函数,如果你做了很多......
其他提示
有可惜substring
未在处理短字符串的方式实现 - 像在其他语言例如蟒。
好了,我们无法改变这一点,有我们每次使用substr
时间来考虑这个边缘的情况下,代替的if-else子句我会去为这个较短的变体:
myText.substring(0, Math.min(6, myText.length()))
您真的需要检查,如果字符串的长度大于或等于38。
我建议阿帕奇公地郎。一个班轮需要照顾的问题。
pstmt2.setString(3, StringUtils.defaultIfEmpty(
StringUtils.subString(itemdescription,0, 38), "_"));
substring(0,38)
意味着字符串必须是38个字符或更长的时间。如果不是,则“字符串索引超出范围”。
if (itemdescription != null && itemdescription.length() > 0) {
pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38)));
} else {
pstmt2.setString(3, "_");
}
我假设你列38个字符的长度,所以要为截 itemdescription
以适应数据库中。像下图的效用函数应该做你想要什么:
/**
* Truncates s to fit within len. If s is null, null is returned.
**/
public String truncate(String s, int len) {
if (s == null) return null;
return s.substring(0, Math.min(len, s.length()));
}
然后你只需要调用它像这样:
String value = "_";
if (itemdescription != null && itemdescription.length() > 0) {
value = truncate(itemdescription, 38);
}
pstmt2.setString(3, value);
爪哇的 substring
当您尝试获取从比字符串长的索引开始的子字符串时,方法会失败。
一个简单的替代方法是使用 阿帕奇共享区 StringUtils.substring
:
public static String substring(String str, int start)
Gets a substring from the specified String avoiding exceptions.
A negative start position can be used to start n characters from the end of the String.
A null String will return null. An empty ("") String will return "".
StringUtils.substring(null, *) = null
StringUtils.substring("", *) = ""
StringUtils.substring("abc", 0) = "abc"
StringUtils.substring("abc", 2) = "c"
StringUtils.substring("abc", 4) = ""
StringUtils.substring("abc", -2) = "bc"
StringUtils.substring("abc", -4) = "abc"
Parameters:
str - the String to get the substring from, may be null
start - the position to start from, negative means count back from the end of the String by this many characters
Returns:
substring from start position, null if null String input
请注意,如果由于某种原因您无法使用 Apache Commons lib,您可以 从源头上获取您需要的零件
// Substring
//-----------------------------------------------------------------------
/**
* <p>Gets a substring from the specified String avoiding exceptions.</p>
*
* <p>A negative start position can be used to start {@code n}
* characters from the end of the String.</p>
*
* <p>A {@code null} String will return {@code null}.
* An empty ("") String will return "".</p>
*
* <pre>
* StringUtils.substring(null, *) = null
* StringUtils.substring("", *) = ""
* StringUtils.substring("abc", 0) = "abc"
* StringUtils.substring("abc", 2) = "c"
* StringUtils.substring("abc", 4) = ""
* StringUtils.substring("abc", -2) = "bc"
* StringUtils.substring("abc", -4) = "abc"
* </pre>
*
* @param str the String to get the substring from, may be null
* @param start the position to start from, negative means
* count back from the end of the String by this many characters
* @return substring from start position, {@code null} if null String input
*/
public static String substring(final String str, int start) {
if (str == null) {
return null;
}
// handle negatives, which means last n characters
if (start < 0) {
start = str.length() + start; // remember start is negative
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY;
}
return str.substring(start);
}
itemdescription
是超过38个字符短。这就是为什么StringOutOfBoundsException
被抛出。
检查.length() > 0
简单地确保了String
有一些不是空值,你需要做的是检查长度足够长的什么样。你可以尝试:
if(itemdescription.length() > 38)
...
您必须检查字符串长度。你认为你可以,只要字符串不是substring(0,38)
做null
,但实际上你需要的字符串,至少38个字符长度。
当此是合适的,我使用匹配强>代替的子强>
使用的子强>:
if( myString.substring(1,17).equals("Someting I expect") ) {
// Do stuff
}
// Does NOT work if myString is too short
使用的匹配强>(必须使用正则表达式表示法):
if( myString.matches("Someting I expect.*") ) {
// Do stuff
}
// This works with all strings
如果 itemdescription 少于 38 个字符,您会得到此信息
您可以查看抛出哪些异常,以及在您的java api中,for string#substring(int,int): https://docs.oracle.com/javase/9/docs/api/java/lang/String.html#substring-int-int-
子串 公共字符串子字符串(int beginIndex,int endIndex) . . . 投掷: 索引越界异常 if the beginIndex is negative, or endIndex 大于此 String 对象的长度, or beginIndex is larger than endIndex. (same applies to previous java versions as well)