If you want to replace substring after 8th
character with an ellipsis, if string length is greater than 10
, you can do it with single String#replaceAll
. You don't even need to check for length before hand. Just use the below code:
A One Liner :
// No need to check for length before hand.
// It will only do a replace if length of str is greater than 10.
// Breaked into multiple lines for explanation
str = str.replaceAll( "^" // Match at the beginning
+ "(.{7})" // Capture 7 characters
+ ".{4,}" // Match 4 or more characters (length > 10)
+ "$", // Till the end.
"$1..."
);
Another option is of course a substring
, which you already have in other answers.