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"
numbers.TrimStart(50); //--> "12345" 
numbers.TrimEnd(50);   //--> "12345"
numbers.Truncate(50);  //->""

In my implementation of TrimStart and TrimEnd methods, 'trim' implies a conditional removal. On overflow, we return entire string. 

This is unlike the, Truncate extension method, which will truncate off the top or the end of the string and in overflow it will return null. See live code below.


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


using System;					
public static class Program
{	
	public static void Main()
	{
		string dq = "\""; 
		string numbers = "12345";
		
		Console.WriteLine(	dq + numbers.TrimStart(1) 	+ dq ); 
		Console.WriteLine(	dq + numbers.TrimStart(50) 	+ dq ); 
		Console.WriteLine(	dq + numbers.TrimEnd(1)		+ dq ); 
		Console.WriteLine(	dq + numbers.TrimEnd(50) 	+ dq ); 
		Console.WriteLine(	dq + numbers.Truncate(1) 	+ dq ); 
		Console.WriteLine(	dq + numbers.Truncate(50) 	+ dq ); 
		
	}
	
	public static string TrimStart(this string input, int length)
	{
		if (string.IsNullOrEmpty(input) || length < 0) return input;
		
		if (length > input.Length) return input;
		
		return input.Substring(length); 
	}
	public static string TrimEnd(this string input, int length)
	{
		if (string.IsNullOrEmpty(input) || length < 1) return input;
		
		if (length > input.Length) return input;
		
		return input.Substring(0, input.Length - length);
	}

	public static string Truncate(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value)) return value;
        return value.Length <= maxLength ? string.Empty : value.Substring(0, maxLength); 
    }
}

No comments:

Post a Comment