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 will contain "abcdefgh..".
How can I achieve this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using
Math.minlike this avoids an exception in the case where the string is already shorter than10.Notes:
The above does simple trimming. If you actually want to replace the last characters with three dots if the string is too long, use Apache Commons
StringUtils.abbreviate; see @H6’s solution. If you want to use the Unicode horizontal ellipsis character, see @Basil’s solution.For typical implementations of
String,s.substring(0, s.length())will returnsrather than allocating a newString.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
charvalues) in theString. By ignoring this, we might trim the string to fewer than 10 code points, or (worse) truncate it in the middle of a surrogate pair. On the other hand,String.length()is not a good measure of Unicode text length, so trimming based on that property may be the wrong thing to do.