Comparing Strings

Hey guys,

I was fiddling around with how I might compare two strings and return a value based on how similar they are. This is the best I came up with and it was surprisingly simple too :smirk:


package 
{
	public class String2
	{		
		public static function compare (arg1:String, arg2:String):Number
		{
			arg1 = arg1.toLowerCase();
			arg2 = arg2.toLowerCase();
			
			var diff:Number = 0;
			
			for(var i:int = 0; i < arg1.length; i++)
			{
				if(arg2.indexOf(arg1.charAt(i)) == -1)
				{
					diff ++;
				}
			}
			
			diff += Math.abs(arg1.length - arg2.length) / arg1.length;
			
			return 1 / (diff + 1);
		}
	}
}

Pretty much self explanatory I think. Compares the first parameter to the second and returns and number between 0 and 1 based on the difference between them.

Thought it might come in useful to some peoples :slight_smile: