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

后端 未结 12 897
醉话见心
醉话见心 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:19

    You can use LINQ str.Take(n) or str.SubString(0, n), where the latter will throw an ArgumentOutOfRangeException exception for n > str.Length.

    Mind that the LINQ version returns a IEnumerable<char>, so you'd have to convert the IEnumerable<char> to string: new string(s.Take(n).ToArray()).

    0 讨论(0)
  • 2020-11-27 13:25
    substring(int startpos, int lenght);
    
    0 讨论(0)
  • 2020-11-27 13:27
    string truncatedToNLength = new string(s.Take(n).ToArray());  
    

    This solution has a tiny bonus in that if n is greater than s.Length, it still does the right thing.

    0 讨论(0)
  • 2020-11-27 13:29

    The .NET Substring method is fraught with peril. I developed extension methods that handle a wide variety of scenarios. The nice thing is it preserves the original behavior, but when you add an additional "true" parameter, it then resorts to the extension method to handle the exception, and returns the most logical values, based on the index and length. For example, if length is negative, and counts backward. You can look at the test results with wide variety of values on the fiddle at: https://dotnetfiddle.net/m1mSH9. This will give you a clear idea on how it resolves substrings.

    I always add these methods to all my projects, and never have to worry about code breaking, because something changed and the index is invalid. Below is the code.

        public static String Substring(this String val, int startIndex, bool handleIndexException)
        {
            if (!handleIndexException)
            { //handleIndexException is false so call the base method
                return val.Substring(startIndex);
            }
            if (string.IsNullOrEmpty(val))
            {
                return val;
            }
            return val.Substring(startIndex < 0 ? 0 : startIndex > (val.Length - 1) ? val.Length : startIndex);
        }
    
        public static String Substring(this String val, int startIndex, int length, bool handleIndexException)
        {
            if (!handleIndexException)
            { //handleIndexException is false so call the base method
                return val.Substring(startIndex, length);
            }
            if (string.IsNullOrEmpty(val))
            {
                return val;
            }
            int newfrom, newlth, instrlength = val.Length;
            if (length < 0) //length is negative
            {
                newfrom = startIndex + length;
                newlth = -1 * length;
            }
            else //length is positive
            {
                newfrom = startIndex;
                newlth = length;
            }
            if (newfrom + newlth < 0 || newfrom > instrlength - 1)
            {
                return string.Empty;
            }
            if (newfrom < 0)
            {
                newlth = newfrom + newlth;
                newfrom = 0;
            }
            return val.Substring(newfrom, Math.Min(newlth, instrlength - newfrom));
        }
    

    I blogged about this back in May 2010 at: http://jagdale.blogspot.com/2010/05/substring-extension-method-that-does.html

    0 讨论(0)
  • 2020-11-27 13:29

    Partially for the sake of summarization (excluding LINQ solution), here's two one-liners that address the int maxLength caveat of allowing negative values and also the case of null string:

    1. The Substring way (from Paul Ruane's answer):
    public static string Truncate(this string s, uint maxLength) =>
        s?.Substring(0, Math.Min(s.Length, (int)maxLength));
    
    1. The Remove way (from kbrimington's answer):
    public static string Truncate(this string s, uint maxLength) =>
        s?.Length > maxLength ? s.Remove((int)maxLength) : s;
    
    0 讨论(0)
  • 2020-11-27 13:29

    string.Substring(0,n); // 0 - start index and n - number of characters

    0 讨论(0)
提交回复
热议问题