Java substring: 'string index out of range'

后端 未结 13 756
眼角桃花
眼角桃花 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: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()))
    

提交回复
热议问题