How to limit the amount of a string printed out (JAVA)
I have a question on how i can limit the amount of a string that is printed out in java. For instance i want something like this:
Orignal String:
"In the long history of the world, 开发者_开发知识库 only a few generations have been granted the role of defending freedom in its hour of maximum danger. I do not shrink from this responsibility - I welcome it. "
I want this:
"In the long history of the world, only a few generations have been granted the role of defending freedom in its hour of maximum..."
Use a java.text.BreakIterator, something like this:
String s = "I want to truncate this";
int chars = 10;
BreakIterator b = BreakIterator.getWordInstance();
b.setText(s);
int cutAt = bi.following(chars);
System.out.println(s.substring(0,cutAt))
You can use something like:
if (s.length() > 25)
System.out.println (s.substring (0,22) + "...");
else
System.out.println (s);
This lets strings that are short enough print as they are, while shortening (with an ellipsis appended) those that are too long.
String yourString = "very long string";
maxCharToPrint= 10;
System.out.println(yourString.substring(0, maxCharToPrint));
String s = "your long sentence"
s.Substring(start, end);
in your case
s.Substring(0, max);
You can also use the Apache Commons' org.apache.commons.lang.StringUtils class, which provides the following utility methods:
String abbreviate(String str, int maxWidth)
String abbreviate(String str, int offset, int maxWidth)
String abbreviateMiddle(String str, String middle, int length)
精彩评论