Java substring: 'string index out of range'

后端 未结 13 748
眼角桃花
眼角桃花 2020-12-03 10:24

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

相关标签:
13条回答
  • 2020-12-03 10:34

    I would recommend apache commons lang. A one-liner takes care of the problem.

    pstmt2.setString(3, StringUtils.defaultIfEmpty(
        StringUtils.subString(itemdescription,0, 38), "_")); 
    
    0 讨论(0)
  • 2020-12-03 10:35

    It is a pity that substring is not implemented in a way that handles short strings – like in other languages e.g. 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:

    myText.substring(0, Math.min(6, myText.length()))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 10:37

    itemdescription is shorter than 38 chars. Which is why the StringOutOfBoundsException is being thrown.

    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:

    if(itemdescription.length() > 38)
      ...
    
    0 讨论(0)
  • 2020-12-03 10:43

    Should anyone face the same problem.

    Do this: str.substring (...(trim()) ;

    Hope it helps somebodies

    0 讨论(0)
  • 2020-12-03 10:46
    if (itemdescription != null && itemdescription.length() > 0) {
        pstmt2.setString(3, itemdescription.substring(0, Math.min(itemdescription.length(), 38))); 
    } else { 
        pstmt2.setString(3, "_"); 
    }
    
    0 讨论(0)
提交回复
热议问题