Java substring: 'string index out of range'

后端 未结 13 776
眼角桃花
眼角桃花 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:55

    I'm assuming your column is 38 characters in length, so you want to truncate itemdescription to fit within the database. A utility function like the following should do what you want:

    /**
     * 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);
    

提交回复
热议问题