Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Chrtran in .NET
Message
From
07/11/2008 12:41:20
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Title:
Environment versions
Environment:
C# 3.0
OS:
Windows XP
Network:
Windows 2003 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
01360482
Message ID:
01360553
Views:
53
This message has been marked as a message which has helped to the initial question of the thread.
>Thanks a lot. I haven't downloaded it yet, but will do soon.
>


Considering that
(1) the ToolKit's implementation of chrtran contains a bug
chrtran("AB", "AB", "BC") yields "CC"
(2) the code in the toolkit was written well before Generics were introduced
- some methods (like inlist) do boxing
- some methods (like between) have functions for int, double, decimal, datetime, ... and cannot be used with other classes unless you overload them again

i think it is better to rewrite some using Generics and extension methods

Here's what I have so far
Console.WriteLine(" {0} ", "AB".ChrTran("AB", "BC"));
// string
namespace GregoryAdam.Base.ExtensionMethods
{
	public static partial class ExtensionMethods
	{
		public static string ChrTran(this string s, string from, string to)
		{
			var sb = new StringBuilder(s, s.Length);

			int i, j;

			for( i = -1; ++i < sb.Length;  )
			{
				if ((j = from.IndexOf(sb[i])) >= 0)
				{
					if (j < to.Length)
					{
						sb[i] = to[j];
					}
					else
					{
						sb.Remove(i--, 1);
					}
				}
			}

			return sb.ToString();
		}

	}
}
Below

- Inlist() should work with any type that implements IEquatable«T»
- Between should work with any type that implements IComparable«T»

Note:
- change « into LessThanSign
- change » into GreaterThanSign
// Generic
namespace GregoryAdam.Base.ExtensionMethods
{

	public static partial class ExtensionMethods
	{
		#region InList
		public static bool InList<T>(this T s, params T[] list) where T : IEquatable«T»
		{
			return list.Contains(s);
		}



		#endregion
		//--------------------------------------------------------------------------------
		#region Between
		public static bool Between<T>(this T s, T s1, T s2) where T : IComparable«T»
		{
			return (s.CompareTo(s1) >= 0) && (s.CompareTo(s2) <= 0);

		}
#if false
		// 3 times slower
		public static bool Between(this IComparable s, IComparable s1, IComparable s2)
		{
			return (s.CompareTo(s1) >= 0) && (s.CompareTo(s2) <= 0);
		}
#endif
		#endregion
		//--------------------------------------------------------------------------------

	}
}
Gregory
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform