How to get the first five character of a String

后端 未结 20 2372
醉酒成梦
醉酒成梦 2020-12-01 05:01

I have read this question to get first char of the string. Is there a way to get the first n number of characters from a string in C#?

20条回答
  •  天涯浪人
    2020-12-01 05:18

    Below is an extension method that checks if a string is bigger than what was needed and shortens the string to the defined max amount of chars and appends '...'.

    public static class StringExtensions
    {
        public static string Ellipsis(this string s, int charsToDisplay)
        {
            if (!string.IsNullOrWhiteSpace(s))
                return s.Length <= charsToDisplay ? s : new string(s.Take(charsToDisplay).ToArray()) + "...";
            return String.Empty;
        }
    }
    

提交回复
热议问题