Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java子字符串:';字符串索引超出范围';_Java_Substring_Indexoutofboundsexception - Fatal编程技术网

Java子字符串:';字符串索引超出范围';

Java子字符串:';字符串索引超出范围';,java,substring,indexoutofboundsexception,Java,Substring,Indexoutofboundsexception,我猜我得到这个错误是因为字符串试图将null值作为子字符串。但是,“.length()>0”部分不是可以消除这个问题吗 以下是Java代码片段: if (itemdescription.length() > 0) { pstmt2.setString(3, itemdescription.substring(0,38)); } else { pstmt2.setString(3, "_"); } 我得到了这个错误: java.lang.StringIndexOut

我猜我得到这个错误是因为字符串试图将
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)

您确实需要检查字符串的长度是否大于或等于38。

子字符串(0,38)
表示字符串必须为38个字符或更长。如果不是,则“字符串索引超出范围”。

itemsdescription
小于38个字符。这就是抛出
StringOutOfBoundsException
的原因

检查
.length()>0
只需确保
字符串
具有一些非空值,您需要做的是检查长度是否足够长。你可以试试:

if(itemdescription.length() > 38)
  ...
我猜我犯了这个错误 因为字符串正在尝试 子字符串为空值。但不会 “.length()>0”部分删除 那个问题

否,当itemdescription为null时调用itemdescription.length()不会生成StringIndexOutOfBoundsException,而是生成NullPointerException,因为您实际上是在null上调用方法

正如其他人所指出的,StringIndexOutOfBoundsException表示itemdescription的长度不超过38个字符。您可能希望处理这两种情况(我假设您希望截断):

最终字符串值;

如果(itemsdescription==null | | itemsdescription.length()我假设您的列的长度为38个字符,因此您希望截断
itemsdescription
以适应数据库。类似于以下的实用程序函数应该满足您的需要:

/**
 * 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);
我推荐。一艘班轮可以解决这个问题

pstmt2.setString(3, StringUtils.defaultIfEmpty(
    StringUtils.subString(itemdescription,0, 38), "_")); 

遗憾的是,
substring
没有以处理短字符串的方式实现,就像在其他语言(如Python)中一样

OK,我们不能改变这一点,每次使用<代码>子字符串< /代码>时,都要考虑这个边缘情况,而不是IF子句,我会选择这个较短的变型:

myText.substring(0, Math.min(6, myText.length()))

Java的
substring
方法在尝试获取从比字符串长的索引开始的子字符串时失败

一个简单的替代方法是使用:

注意,如果出于某种原因不能使用ApacheCommons库,您可以

//子字符串
//-----------------------------------------------------------------------
/**
*从指定的字符串中获取子字符串以避免异常

* *负起始位置可用于启动{@code n} *字符串末尾的字符

* *A{@code null}字符串将返回{@code null}。 *空(“”)字符串将返回“”

* * *StringUtils.substring(null,*)=null *StringUtils.substring(“,*)=” *StringUtils.子字符串(“abc”,0)=“abc” *StringUtils.子字符串(“abc”,2)=“c” *StringUtils.子字符串(“abc”,4)=“” *StringUtils.substring(“abc”,-2)=“bc” *StringUtils.substring(“abc”,-4)=“abc” * * *@param str获取子字符串的字符串可能为空 *@param start起始位置,负值表示起始位置 *从字符串末尾开始倒数这么多字符 *@从起始位置返回子字符串,{@code null}如果输入空字符串 */ 公共静态字符串子字符串(最终字符串str,int start){ 如果(str==null){ 返回null; } //处理负数,这意味着最后n个字符 如果(开始<0){ start=str.length()+start;//记住start是负数 } 如果(开始<0){ 开始=0; } 如果(开始>长度(){ 返回空; } 返回str.substring(开始); }
您必须检查字符串长度。您假设只要字符串不是
null
,就可以执行
子字符串(0,38)
,但实际上您需要字符串长度至少为38个字符。

如果itemdescription短于38个字符,则会得到此结果

您可以查看抛出了哪些异常以及何时在JavaAPI中抛出 对于字符串#子字符串(int,int):

子串 公共字符串子字符串(int beginIndex、int endIndex) . . . 抛出: IndexOutOfBoundsException 如果beginIndex为负值, 或endIndex大于此字符串对象的长度, 或者beginIndex大于endIndex。 (这同样适用于以前的java版本)
如果合适,我使用匹配而不是子字符串

子字符串的

if( myString.matches("Someting I expect.*") ) {
    // Do stuff
}
// This works with all strings
匹配时(必须使用正则表达式表示法):


任何人都应该面对同样的问题

pstmt2.setString(3, StringUtils.defaultIfEmpty(
    StringUtils.subString(itemdescription,0, 38), "_")); 
这样做: str.substring(…(trim())


希望它能帮助一些人,我真的很想知道itemdescription.substring(0,itemdescription.length())将返回什么:)var itemdescription=新字符串(“Hello,World!”);alert(itemdescription.substring(0,itemdescription.length));返回“Hello,World!”!“。他可能想用它做点什么。嗯,是的,应该有一个上限。这是你的午夜发帖……是的,这太荒谬了。在大多数情况下,将字符串与
==
进行比较是不可行的。模式匹配与字符串比较有很大不同,在这种情况下,这是一个坏主意,尤其是(但不仅如此)出于性能方面的原因。你是对的,Alexandre;更改为equals。我发现正则表达式非常方便且易于使用,但它的性能较差也是对的。它不起作用。
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
// 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);
}
substring public String substring(int beginIndex, int endIndex) . . . Throws: IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex. (same applies to previous java versions as well)
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