What method in the String class returns only the first N characters?

后端 未结 12 983
醉话见心
醉话见心 2020-11-27 12:27

I\'d like to write an extension method to the String class so that if the input string to is longer than the provided length N, only the first

12条回答
  •  独厮守ぢ
    2020-11-27 13:16

    Whenever I have to do string manipulations in C#, I miss the good old Left and Right functions from Visual Basic, which are much simpler to use than Substring.

    So in most of my C# projects, I create extension methods for them:

    public static class StringExtensions
    {
        public static string Left(this string str, int length)
        {
            return str.Substring(0, Math.Min(length, str.Length));
        }
    
        public static string Right(this string str, int length)
        {
            return str.Substring(str.Length - Math.Min(length, str.Length));
        }
    }
    

    Note:
    The Math.Min part is there because Substring throws an ArgumentOutOfRangeException when the input string's length is smaller than the requested length, as already mentioned in some comments under previous answers.

    Usage:

    string longString = "Long String";
    
    // returns "Long";
    string left1 = longString.Left(4);
    
    // returns "Long String";
    string left2 = longString.Left(100);
    

提交回复
热议问题