Trim a string based on the string length

后端 未结 12 875
無奈伤痛
無奈伤痛 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:22

    s = s.substring(0, Math.min(s.length(), 10));
    

    Using Math.min like this avoids an exception in the case where the string is already shorter than 10.


    Notes:

    1. The above does real trimming. If you actually want to replace the last three (!) characters with dots if it truncates, then use Apache Commons StringUtils.abbreviate.

    2. For typical implementations of String, s.substring(0, s.length()) will return s rather than allocating a new String.

    3. This may behave incorrectly1 if your String contains Unicode codepoints outside of the BMP; e.g. Emojis. For a (more complicated) solution that works correctly for all Unicode code-points, see @sibnick's solution.


    1 - A Unicode codepoint that is not on plane 0 (the BMP) is represented as a "surrogate pair" (i.e. two char values) in the String. By ignoring this, we might trim to fewer than 10 code points, or (worse) truncate in the middle of a surrogate pair. On the other hand, String.length() is no longer an ideal measure of Unicode text length, so trimming based on it may be the wrong thing to do.

提交回复
热议问题