Trim a string based on the string length

后端 未结 12 867
無奈伤痛
無奈伤痛 2020-12-12 14:29

I want to trim a string if the length exceeds 10 characters.

Suppose if the string length is 12 (String s=\"abcdafghijkl\"), then the new trimmed string

12条回答
  •  粉色の甜心
    2020-12-12 15:06

    There is a Apache Commons StringUtils function which does this.

    s = StringUtils.left(s, 10)
    

    If len characters are not available, or the String is null, the String will be returned without an exception. An empty String is returned if len is negative.

    StringUtils.left(null, ) = null
    StringUtils.left(
    , -ve) = ""
    StringUtils.left("", *) = ""
    StringUtils.left("abc", 0) = ""
    StringUtils.left("abc", 2) = "ab"
    StringUtils.left("abc", 4) = "abc"

    StringUtils.Left JavaDocs

    Courtesy:Steeve McCauley

提交回复
热议问题