Friday, July 13, 2018

C# TrimStart and TrimEnd with integer length parameter string extensions

This C# code overloads TrimStart and TrimEnd methods, adding an integer length parameter which  provides a more intuitive method call.
 

string numbers = "12345";
numbers.TrimStart(1);  //--> "2345" 
numbers.TrimEnd(1);    //--> "1234"

Many others have called this a string Truncate extension method, which is ambiguous because truncate means to shorten (something) by cutting off the top or the end. 

Below is the code to add TrimStart(int length) and TrimEnd(int length) methods signatures added using string extension methods.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
    public static class StringExtensions
    {
        //Note: Intuitive method names, IMHO metadataconsult@gmail.com 
        //      Prefered method signature with uint, but introduces a range issue UNIT (4294967295) > INT (+/-2147483647) and therefore misleading 
        //      Be great if c# had a UINT which was same size as INT (2147483647)
   
        /// <summary>
        /// Gets string removing a length from start of string 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="length">remove length from start of input, returning remaining string to end</param>
        /// <returns>Bonus: if index is greater that length, returns the full string</returns>
        public static string TrimStart(this string input, int length)
        {
            if (string.IsNullOrEmpty(input) || length < 0) return input;
            
            if (length > input.Length) return input; //bonus

            return input.Substring(length); 
        }
        /// <summary>
        /// Gets string less length from end
        /// </summary>
        /// <param name="input"></param>
        /// <param name="length">remove length from end of input, returning remaining string from start</param> 
        /// <returns>Bonus: if index is greater that length, returns empty string</returns>
        public static string TrimEnd(this string input, int length)
        {
            if (string.IsNullOrEmpty(input) || length < 1) return input;

            if (length > input.Length) return  ""; //bonus

            return input.Substring(0, input.Length - length);
        }
    }

No comments:

Post a Comment