Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
StrTran() and StrTranCaseInsensitive()
Message
From
05/04/2010 07:43:39
 
General information
Forum:
VB.NET
Category:
Other
Title:
StrTran() and StrTranCaseInsensitive()
Environment versions
Environment:
C# 3.0
Miscellaneous
Thread ID:
01458703
Message ID:
01458703
Views:
137
Michel,

(1) StrTran()
I do not think you need the StringBuilder() as String.Replace() will do as well

(2) StrTranCaseInsensitive()

May I suggest an alternative that uses IndexOf(). Can be used as a static method or as an extension method
using System.Text;
using GregoryAdam.Base.ExtensionMethods;
namespace BaseTest
{
	class test3
	{


		//______________________________________________________________________
		static void Main()
		{

			Console.WriteLine("{0}", "hello".Replace("o", "123", StringComparison.InvariantCultureIgnoreCase));
			Console.ReadLine();
		}

	}
}
namespace GregoryAdam.Base.ExtensionMethods
{
	public static partial class ExtensionMethods_String_Replace
	{
	
		//______________________________________________________________________
		/// <summary>
		/// Replaces every occurrence of oldValue with newValue
		/// </summary>
		/// <param name="s"></param>
		/// <param name="oldValue">The string to be replaced</param>
		/// <param name="newValue">The string that replaces all occurrences of oldValue
		/// <para>May be null or the empty string</para></param>
		/// <param name="stringComparison"></param>
		/// <returns></returns>
		public static string Replace(
				this string s, 
				string oldValue, 
				string newValue, 
				StringComparison stringComparison
			)
		{
			if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(oldValue))
				return s;
			
			int offset = 0;
			int n = s.IndexOf(oldValue, offset, stringComparison);

			if (n < 0 )
				return s;

			int oldLength = oldValue.Length;
			bool isNewValueNullOrEmpty = string.IsNullOrEmpty(newValue);

			StringBuilder sb = new StringBuilder();

			do
			{
				if (n - offset > 0)
					sb.Append(s, offset, n - offset);

				if( !isNewValueNullOrEmpty )		
					sb.Append(newValue);

				offset = n + oldLength;
			}
			while ((n = s.IndexOf(oldValue, offset, stringComparison)) >= 0);

			if( offset < s.Length )
				sb.Append(s, offset, s.Length - offset);

			return sb.ToString();
		
		}
		//______________________________________________________________________
	}
}
Gregory
Next
Reply
Map
View

Click here to load this message in the networking platform