March 20, 2007

substring-before()/substring-after() for C#

XSLT isn't the best language for string processing, but it (XPath actually) has a very handy pair of substring functions: substring-before() and substring-after(). I used to write XSLT a lot and always missed them in C# or Java. Yes, C# and Java have indexOf() and regex, but indexOf() is too low-level ...

Anyway, here is the code:

using System;
using System.Linq;
using System.Globalization;

namespace XmlLab.Extensions
{
    public static class StringExtensions
    {
        public static string SubstringAfter(this string source, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return source;
            }
            CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo;            
            int index = compareInfo.IndexOf(source, value, CompareOptions.Ordinal);
            if (index < 0)
            {
                //No such substring
                return string.Empty;
            }
            return source.Substring(index + value.Length);            
        }

        public static string SubstringBefore(this string source, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return value;
            }
            CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo;
            int index = compareInfo.IndexOf(source, value, CompareOptions.Ordinal);
            if (index < 0)
            {
                //No such substring
                return string.Empty;                    
            }
            return source.Substring(0, index);
        }
    }
}