【问题标题】:How to add "..." on a trimmed string?如何在修剪后的字符串上添加“...”?
【发布时间】:2013-12-02 23:59:53
【问题描述】:

我已经将字符串的 maxLength 设置为 100,所以我需要前 97 个字符是普通字符,但后三个必须是“...”。

尝试在字符串中添加+“...”,但是,当它达到限制时,自然无法添加任何内容。

如何解决这个问题?

谢谢!

【问题讨论】:

    标签: java android string text trim


    【解决方案1】:

    你还没有提到你为什么要修剪字符串。 如果您正在修剪它以在 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"/>
    

    (如果我错了,这与 TextViews 无关,请忽略此答案 :))

    【讨论】:

    • 我很抱歉在这些条款上没有那么具体,但这就是我正在寻找的答案! :) 谢谢! :D
    【解决方案2】:

    应对各种长度字符串的解决方案:

    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;
    }
    

    【讨论】:

      【解决方案3】:

      在将字符串放在一起时,您几乎应该总是使用StringBuilder。在这种情况下,您可以调用setCharAt() 来更改最后三个字符。如果您确实确实需要直接使用String,请使用substring() 捕获前97 个字符,然后添加省略号。

      【讨论】:

        【解决方案4】:

        如下使用String#substring

        int maxLength = 100;
        String lastThree = "...";
        return str.substring(0, maxLength - lastThree.length()) + "...");
        

        一个工作示例:

        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);
                }
            }
        }
        

        【讨论】:

        猜你喜欢
        • 2021-06-25
        • 2011-06-06
        • 1970-01-01
        • 1970-01-01
        • 2022-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        相关资源
        最近更新 更多