I have a very long string like "The event for mobile" they can be any length strings ,i want to show .... after say certain length ,how to do this ?
Asked
Active
Viewed 1.7k times
6 Answers
4
Use Apache Common library's WordUtils class.
static String wrap(java.lang.String str,
int wrapLength, java.lang.String newLineStr, boolean wrapLongWords)
example -
String str = "This is a sentence that we're using to test the wrap method";
System.out.println("Original String 1:\n" + str);
System.out.println("\nWrap length of 10:\n" + WordUtils.wrap(str, 10));
System.out.println("\nWrap length of 20:\n" + WordUtils.wrap(str, 20));
System.out.println("\nWrap length of 30:\n" + WordUtils.wrap(str, 30));

yurez
- 2,826
- 1
- 28
- 22

Subhrajyoti Majumder
- 40,646
- 13
- 77
- 103
3
You can do something like this -
String str = "The event for mobile is here";
String temp = "";
if(str !=null && str.length() > 10) {
temp = str.substring(0, 10) + "...."; // here 0 is start index and 10 is last index
} else {
temp = str;
}
System.out.println(temp);
output would be - The event ....

Pramod Kumar
- 7,914
- 5
- 28
- 37
1
String template = "Hello I Am A Very Long String";
System.out.println(template.length() > 10 ? template.substring(0, 10) + "..." : template);
You can just look at the length and then do a substring
.
Or if you can use Apache's common Util then use this WordUtils.wrap().
I didn't do a good search earlier, this SO Post is exactly what you want
1
If you want full words then do this:
public static void shortenStringFullWords(String str, int maxLength) {
StringBuilder output = new StringBuilder();
String[] tokens = str.split(" ");
for (String token: tokens) {
if (output.length() + token.length <= maxLength - 3) {
output.append(token);
output.append(" ");
} else {
return output.toString().trim() + "...";
}
}
return output.toString().trim();
}

fardjad
- 20,031
- 6
- 53
- 68
1
You can do this like this
String longString = "lorem ipusum ver long string";
String shortString = "";
int maxLength = 5;
if(longString != null && longString.length() > maxLength) {
shortString = longString.substring(0,maxLength - 1)+"...";
}
Here, you can change maxLength to your desired number.

Felix Christy
- 2,179
- 1
- 19
- 32
1
String myString ="my lengthy string";
int startIndex=0, endIndex=myString.length(), lengthLimit = 10;
while(startIndex<endIndex) {
System.out.println(myString.substring(startIndex, startIndex+lengthLimit));
startIndex = startIndex+lengthLimit+1;
}

Raghu Nagaraju
- 3,278
- 1
- 18
- 25