我想为String类编写一个扩展方法,以便如果输入字符串比提供的长度N长,则只显示前N个字符。

这是它的样子:

public static string TruncateLongString(this string str, int maxLength)
{
    if (str.Length <= maxLength)
        return str;
    else
        //return the first maxLength characters                
}

什么字符串.*()方法我可以使用只得到str的前N个字符?


当前回答

你可以使用LINQ str.Take(n)或str.SubString(0, n),后者将为n > str.Length抛出ArgumentOutOfRangeException异常。

注意,LINQ版本返回一个IEnumerable<char>,所以你必须将IEnumerable<char>转换为string: new string(s.t take (n). toarray())。

其他回答

如果我们还在讨论验证,为什么我们没有检查空字符串条目。有什么具体原因吗?

我认为下面的方式帮助,因为IsNullOrEmpty是一个系统定义的方法,三元操作符的圈复杂度= 1,而if() {} else{}的值为2。

    public static string Truncate(string input, int truncLength)
    {
        return (!String.IsNullOrEmpty(input) && input.Length >= truncLength)
                   ? input.Substring(0, truncLength)
                   : input;
    }

部分为了总结(不包括LINQ解决方案),这里有两个一行程序,解决了int maxLength允许负值的警告和空字符串的情况:

Substring方式(来自Paul Ruane的回答):

public static string Truncate(this string s, uint maxLength) =>
    s?.Substring(0, Math.Min(s.Length, (int)maxLength));

移除方式(来自kbrimington的回答):

public static string Truncate(this string s, uint maxLength) =>
    s?.Length > maxLength ? s.Remove((int)maxLength) : s;

你可以使用LINQ str.Take(n)或str.SubString(0, n),后者将为n > str.Length抛出ArgumentOutOfRangeException异常。

注意,LINQ版本返回一个IEnumerable<char>,所以你必须将IEnumerable<char>转换为string: new string(s.t take (n). toarray())。

public static string TruncateLongString(this string str, int maxLength)
{
    return str.Length <= maxLength ? str : str.Remove(maxLength);
}

我在我的项目中添加了这个,只是因为我使用它的地方是一个很高的机会,它被循环使用,在一个在线托管的项目中,因此我不希望任何崩溃,如果我能管理它。长度符合我的一列。这是C # 7

只有一句话:

 public static string SubStringN(this string Message, int Len = 499) => !String.IsNullOrEmpty(Message) ? (Message.Length >= Len ? Message.Substring(0, Len) : Message) : "";