Click here to Skip to main content
15,895,797 members
Articles / Programming Languages / C#

Fastest C# Case Insenstive String Replace

Rate me:
Please Sign up or sign in to vote.
4.72/5 (30 votes)
4 Jul 20052 min read 353.9K   1.6K   59  
Find a fast way to replace case insenstive string.
using System;
using System.Text;

namespace StringHelperTest
{
	public class StringHelper
	{

		public enum CompareMethods
		{
			Text,
			Binary
		}

		public static string ReplaceText(string Expression,
			string SearchText,
			string ReplaceText,
			CompareMethods Method)
		{
			string result;
			int position;
			string temp;

			if(Method == CompareMethods.Text) 
			{
				result = "";
				SearchText = SearchText.ToUpper();
				temp = Expression.ToUpper();
				position = temp.IndexOf(SearchText);
				while(position >= 0)
				{
					result = result + Expression.Substring(0,position) + ReplaceText;
					Expression = Expression.Substring(position + SearchText.Length);
					temp = temp.Substring(position+SearchText.Length);
					position = temp.IndexOf(SearchText);
				}
				result = result + Expression;
			} 
			else 
			{
				result = Expression.Replace(SearchText,ReplaceText);
			}

			return result;
		}

		public static string ReplaceTextB(string Expression,
			string SearchText,
			string ReplaceText,
			CompareMethods Method)
		{
			StringBuilder result;
			int position;
			string temp;

			if(Method == CompareMethods.Text) 
			{
				result = new StringBuilder();
				SearchText = SearchText.ToUpper();
				temp = Expression.ToUpper();
				position = temp.IndexOf(SearchText);
				while(position >= 0)
				{
					result.Append(Expression.Substring(0,position) + ReplaceText);
					Expression = Expression.Substring(position + SearchText.Length);
					temp = temp.Substring(position+SearchText.Length);
					position = temp.IndexOf(SearchText);
				}
				result.Append(Expression);
				return result.ToString();
			} 
			else 
			{
				return Expression.Replace(SearchText,ReplaceText);
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Product Manager www.xnlab.com
Australia Australia
I was born in the south of China, started to write GWBASIC code since 1993 when I was 13 years old, with professional .net(c#) and vb, founder of www.xnlab.com

Now I am living in Sydney, Australia.

Comments and Discussions