Pergunta
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 ?
Solução
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 ....
Outras dicas
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));
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
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();
}
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.
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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow