[英]How to add “…” on a trimmed string?
I've set the maxLength of the string to 100, so I need that the first 97 characters are normal chars, but the last three have to be "...". 我已将字符串的maxLength设置为100,因此我需要前97个字符为普通字符,但后三个字符必须为“ ...”。
Tried to add +"..." to the string, but, naturally, when it reaches the limit, nothing can be added there. 试图在字符串中添加+“ ...”,但是很自然,当达到极限时,不能在其中添加任何内容。
How to fix this? 如何解决这个问题?
Thanks! 谢谢!
You haven't mentioned why are you trimming the String. 您没有提到为什么要修剪字符串。 If you are trimming it to use it in TextView/Button/etc, don't forget you can use maxLines and ellipsize to achieve desired effect.
如果您要修剪它以便在TextView / Button / etc中使用它,请不要忘记可以使用maxLines和ellipsize来实现所需的效果。
<TextView
android:id="@+id/myText"
android:maxLines="1"
android:ellipsize="end"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
(If I am wrong and this has nothing to do with TextViews, just ignore this answer :)) (如果我错了,并且与TextViews无关,则忽略此答案:))
A solution that copes with strings of all length: 解决所有长度字符串的解决方案:
String trim(String string, int maxLength)
{
if (maxLength < 3)
throw new IllegalArgumentException("Max length (" + maxLength + ") must at least 3");
return string.length() > maxLength ?
string.substring(0, maxLength - 3) + "..." :
string;
}
Use String#substring
as follows: 使用
String#substring
,如下所示:
int maxLength = 100;
String lastThree = "...";
return str.substring(0, maxLength - lastThree.length()) + "...");
A working example: 一个工作示例:
public class Test {
static final String str = "redgreenblue";
static final String t = "...";
public static void main(String[] args) {
try {
System.out.println(str.substring(0,10-t.length()) + t);
}
catch (StringIndexOutOfBoundsException e) {
System.out.println(str + t);
}
}
}
You should almost always use a StringBuilder
when putting a string together. 将字符串放在一起时,几乎应该始终使用
StringBuilder
。 In this case, you can call setCharAt()
to change the last three characters. 在这种情况下,可以调用
setCharAt()
更改最后三个字符。 If you really really do need to use a String
directly, use substring()
to capture the first 97 characters and then add the ellipsis. 如果确实确实需要直接使用
String
,请使用substring()
捕获前97个字符,然后添加省略号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.