I would like to cut a Java String when this String length is > 50, and add "..." at the end of the string.
Example :
I have the following Java String :
String str = "abcdefghijklmnopqrtuvwxyz";
I would like to cut the String at length = 8 :
Result must be:
String strOut = "abcdefgh..."
Using the String#split Method As the name implies, it splits a string into multiple parts based on a given delimiter or regular expression. As we can see, we used the regex (? <=\\G. {” + n + “}) where n is the number of characters.
To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.
Java String split() The String split() method returns an array of split strings after the method splits the given string around matches of a given regular expression containing the delimiters. The regular expression must be a valid pattern and remember to escape special characters if necessary.
Use substring and concatenate:
if(str.length() > 50) strOut = str.substring(0,7) + "...";
StringUtils.abbreviate("abcdefg", 6);
This will give you the following result: abc...
Where 6 is the needed length, and "abcdefg" is the string that needs to be abbrevieted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With