Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cut Java String at a number of character

Tags:

java

string

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..." 
like image 696
wawanopoulos Avatar asked Jul 16 '13 20:07

wawanopoulos


People also ask

How can I split a string into segments of N characters Java?

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.

How do you cut a string upto a certain character?

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.

Can you split a string by multiple characters Java?

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.


2 Answers

Use substring and concatenate:

if(str.length() > 50)     strOut = str.substring(0,7) + "..."; 
like image 172
Sir Pakington Esq Avatar answered Oct 05 '22 15:10

Sir Pakington Esq


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.

like image 37
Mike Shadoff Avatar answered Oct 05 '22 17:10

Mike Shadoff