【问题标题】:Long path with ellipsis in the middle [duplicate]中间有省略号的长路径[重复]
【发布时间】:2011-12-06 16:12:28
【问题描述】:

我想将长路径截断为特定长度。但是,我想在中间加上省略号。

例如:\\my\long\path\is\really\long\and\it\needs\to\be\truncated 应该变成(截断为 35 个字符):\\my\long\path\is...to\be\truncated

是否有可用的标准函数或扩展方法?

【问题讨论】:

标签: c#


【解决方案1】:

没有标准的函数或扩展方法,所以你必须自己动手。

检查长度并使用类似的东西;

var truncated = ts.Substring(0, 16) + "..." + ts.Substring((ts.Length - 16), 16);

【讨论】:

  • @Elmue 感谢您对已有近 10 年历史的内容提供意见...您阅读了要求吗?您是否声称要求是错误的并且您的答案必须是正确的,因为这是您可能想要使用截断字符串的唯一方法?
  • @Elmue 您似乎在做出假设,这是您的习惯吗?从那时起,我的解决方案对提出问题的人和其他一些人很有用,因此绿色勾号的原因以及它上面的大于 0 的数字。
【解决方案2】:

这是我使用的。它可以很好地在路径中间创建省略号,还允许您指定任何长度或分隔符。

注意这是一个扩展方法,所以你可以像这样使用它`"c:\path\file.foo".EllipsisString()

我怀疑你是否需要 while 循环,事实上你可能不需要,我只是太忙了,无法正确测试

    public static string EllipsisString(this string rawString, int maxLength = 30, char delimiter = '\\')
    {
        maxLength -= 3; //account for delimiter spacing

        if (rawString.Length <= maxLength)
        {
            return rawString;
        }

        string final = rawString;
        List<string> parts;

        int loops = 0;
        while (loops++ < 100)
        {
            parts = rawString.Split(delimiter).ToList();
            parts.RemoveRange(parts.Count - 1 - loops, loops);
            if (parts.Count == 1)
            {
                return parts.Last();
            }

            parts.Insert(parts.Count - 1, "...");
            final = string.Join(delimiter.ToString(), parts);
            if (final.Length < maxLength)
            {
                return final;
            }
        }

        return rawString.Split(delimiter).ToList().Last();
    }

【讨论】:

    【解决方案3】:

    这行得通

        // Specify max width of resulting file name
        const int MAX_WIDTH = 50;
    
        // Specify long file name
        string fileName = @"A:\LongPath\CanBe\AnyPathYou\SpecifyHere.txt";
    
        // Find last '\' character
        int i = fileName.LastIndexOf('\\');
    
        string tokenRight = fileName.Substring(i, fileName.Length - i);
        string tokenCenter = @"\...";
        string tokenLeft = fileName.Substring(0, MAX_WIDTH-(tokenRight.Length + tokenCenter.Length));
    
        string shortFileName = tokenLeft + tokenCenter + tokenRight;
    

    【讨论】:

    • 我喜欢这种方法,唯一的问题是如果文件名太大(如果 tokenCenter 一起大于 max_width),它会破坏 tokenLeft 计算,并出现 ArgumentException,因为尝试使用负值。
    猜你喜欢
    • 1970-01-01
    • 2019-12-11
    • 2020-07-29
    • 2018-10-06
    • 2014-09-16
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    相关资源
    最近更新 更多