Thursday, 23 September 2010

C# Left() and Right() String Extensions

Classic ASP developers will recognise these two handy methods for grabbing a specific number of characters from the start or end of a string.  They've proven to be quite useful to me in the past with my VBScript development.

I decided the best way to use them in future would be to convert them to string extension methods in C#. This allows you to simply call the method on an existing string.

 
    namespace BaseFour.Extensions
    {
        public class StringExtensions
        {
            public static string Left(this string s, int characters)
            {
                if (characters < 0)
                    throw new ArgumentOutOfRangeException();
                if (characters > s.Length)
                    characters = s.Length;
                return s.Substring(0, characters);
            }
    
            public static string Right(this string s, int characters)
            {
                if (characters < 0)
                    throw new ArgumentOutOfRangeException();
                if (characters > s.Length)
                    characters = s.Length;
                return s.Substring(s.Length - characters, characters);
            }
        }
    }
 

Usage:

 
    string value = "SuperDuper";

    value.Left(5); // Super
    value.Right(5); // Duper
 

They are great for doing some simple trailing slash checking for directories and urls before processing.

No comments:

Post a Comment