Java子字符串:'字符串索引超出范围'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/953527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java substring: 'string index out of range'
提问by phill
I'm guessing I'm getting this error because the string is trying to substring a null
value. But wouldn't the ".length() > 0"
part eliminate that issue?
我猜我收到此错误是因为该字符串正在尝试对null
值进行子字符串化。但是这".length() > 0"
部分不会消除这个问题吗?
Here is the Java snippet:
这是Java片段:
if (itemdescription.length() > 0) {
pstmt2.setString(3, itemdescription.substring(0,38));
}
else {
pstmt2.setString(3, "_");
}
I got this error:
我收到此错误:
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)
采纳答案by Bert F
I"m guessing i'm getting this error because the string is trying to substring a Null value. But wouldn't the ".length() > 0" part eliminate that issue?
我猜我收到这个错误是因为字符串试图对空值进行子字符串化。但是“.length() > 0”部分不会消除这个问题吗?
No, calling itemdescription.length() when itemdescription is null would not generate a StringIndexOutOfBoundsException, but rather a NullPointerException since you would essentially be trying to call a method on null.
不,当 itemdescription 为 null 时调用 itemdescription.length() 不会生成 StringIndexOutOfBoundsException ,而是生成 NullPointerException ,因为您实际上是在尝试调用null上的方法。
As others have indicated, StringIndexOutOfBoundsException indicates that itemdescription is not at least 38 characters long. You probably want to handle both conditions (I assuming you want to truncate):
正如其他人所指出的,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);
Might be a good place for a utility function if you do that a lot...
如果你经常这样做,可能是一个实用函数的好地方......
回答by Jase Whatson
You really need to check if the string's length is greater to or equal to 38.
您确实需要检查字符串的长度是否大于或等于 38。
回答by Apocalisp
substring(0,38)
means the String has to be 38 characters or longer. If not, the "String index is out of range".
substring(0,38)
意味着字符串必须是 38 个字符或更长。如果不是,则“字符串索引超出范围”。
回答by pugmarx
itemdescription
is shorter than 38 chars. Which is why the StringOutOfBoundsException
is being thrown.
itemdescription
少于 38 个字符。这就是StringOutOfBoundsException
被抛出的原因。
Checking .length() > 0
simply makes sure the String
has some not-null value, what you need to do is check that the length is long enough. You could try:
检查.length() > 0
只是确保String
具有一些非空值,您需要做的是检查长度是否足够长。你可以试试:
if(itemdescription.length() > 38)
...
回答by JeeBee
if (itemdescription != null && itemdescription.length() > 0) {
pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38)));
} else {
pstmt2.setString(3, "_");
}
回答by Chris Gow
I'm assuming your column is 38 characters in length, so you want to truncateitemdescription
to fit within the database. A utility function like the following should do what you want:
我假设您的列长度为 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()));
}
then you just call it like so:
那么你就这样称呼它:
String value = "_";
if (itemdescription != null && itemdescription.length() > 0) {
value = truncate(itemdescription, 38);
}
pstmt2.setString(3, value);
回答by H Marcelo Morales
I would recommend apache commons lang. A one-liner takes care of the problem.
我会推荐apache commons lang。one-liner 可以解决这个问题。
pstmt2.setString(3, StringUtils.defaultIfEmpty(
StringUtils.subString(itemdescription,0, 38), "_"));
回答by linqu
It is a pity that substring
is not implemented in a way that handles short strings –?like in other languages e.g. Python.
遗憾的是,substring
它没有以处理短字符串的方式实现——就像在其他语言中一样,例如 Python。
Ok, we cannot change that and have to consider this edge case every time we use substr
, instead of if-else clauses I would go for this shorter variant:
好的,我们不能改变它,每次使用时都必须考虑这种边缘情况substr
,而不是 if-else 子句,我会选择这个较短的变体:
myText.substring(0, Math.min(6, myText.length()))
回答by Brad Parks
Java's substring
method fails when you try and get a substring starting at an index which is longer than the string.
substring
当您尝试从比字符串长的索引开始获取子字符串时,Java 的方法失败。
An easy alternative is to use Apache Commons StringUtils.substring
:
一个简单的替代方法是使用Apache CommonsStringUtils.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
Note, if you can't use Apache Commons lib for some reason, you could just grab the parts you need from the source
请注意,如果由于某种原因您不能使用 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);
}
回答by sixtytrees
You must check the String length. You assume that you can do substring(0,38)
as long as String is not null
, but you actually need the String to be of at least 38 characters length.
您必须检查字符串长度。您假设substring(0,38)
只要 String is not就可以执行null
,但实际上您需要 String 的长度至少为 38 个字符。