Case Insensitive String Extension Method

Posted on: Wed Feb 10 18:08:16 -0800 2010. Updated on: Wed Feb 10 18:10:24 -0800 2010.
Category: .NET C#

The default String.Replace is not case Insensitive, here is a quick extension method you could add to get a String.ReplaceCI that would do this. I like extension methods.

public static class StringExtensions
	{
		public static string ReplaceCI(this String sourceString, string searchString, string replaceString)
		{
			if (searchString == null) throw new ArgumentNullException("searchString");
			if (replaceString == null) throw new ArgumentNullException("replaceString");
			StringBuilder retVal = new StringBuilder(sourceString.Length);

			int ptr = 0, lastPtr = 0;

			while (ptr >= 0)
			{
				ptr = sourceString.IndexOf(searchString, ptr, StringComparison.OrdinalIgnoreCase);

				int strLength = ptr - lastPtr;
				if (strLength > 0 || ptr == 0)
				{
					if (ptr > 0)
						retVal.Append(sourceString.Substring(lastPtr, strLength));

					retVal.Append(replaceString);
					ptr += searchString.Length;
				}
				else
					break;

				lastPtr = ptr;
			}

			if (lastPtr >= 0) 
				retVal.Append(sourceString.Substring(lastPtr));

			return retVal.ToString();
		}
}

Ideas were borrowed from this guy: Case Insensitive String

Comments:

Add a Comment:

simple_captcha.jpg
(human authentication)


Ads

Categories

About

Random foliage

This website is meant to be a reference for ASP Dot Net developers. The entries are a compilation of things I've figured out how to do and that I deem useful to keep of track for future reference. Assumptions: web development with: C Sharp (vb sucks), visual studio 05/08, .net 3.5, meant for programmers. Written by: James Reategui.