获取前25个字符的微小方法 [英] Tiny way to get the first 25 characters

查看:47
本文介绍了获取前25个字符的微小方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以想到一种更好的方法来进行以下操作:

Can anyone think of a nicer way to do the following:

public string ShortDescription
{
    get { return this.Description.Length <= 25 ? this.Description : this.Description.Substring(0, 25) + "..."; }
}

我只想做string.Substring(0,25),但是如果字符串小于提供的长度,它将引发异常.

I would have liked to just do string.Substring(0, 25) but it throws an exception if the string is less than the length supplied.

推荐答案

我经常需要这样做,为此我写了一个扩展方法:

I needed this so often, I wrote an extension method for it:

public static class StringExtensions
{
    public static string SafeSubstring(this string input, int startIndex, int length, string suffix)
    {
        // Todo: Check that startIndex + length does not cause an arithmetic overflow - not that this is likely, but still...
        if (input.Length >= (startIndex + length))
        {
            if (suffix == null) suffix = string.Empty;
            return input.Substring(startIndex, length) + suffix;
        }
        else
        {
            if (input.Length > startIndex)
            {
                return input.Substring(startIndex);
            }
            else
            {
                return string.Empty;
            }
        }
    }
}

如果只需要一次,那就太过分了,但是如果您经常使用它,那么它会派上用场.

if you only need it once, that is overkill, but if you need it more often then it can come in handy.

添加了对字符串后缀的支持.传递"...",您会在较短的字符串上出现椭圆,或者传递字符串.如果没有特殊后缀,则为空.

Added support for a string suffix. Pass in "..." and you get your ellipses on shorter strings, or pass in string.Empty for no special suffixes.

这篇关于获取前25个字符的微小方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆