.netalgorithmstring-comparison

Seeking an algorithm or approach to compare values between two strings (.NET)


I have a problem with a piece of data as a string, and I have to check if the data exists between the stated ranges.

Note that if both ends are numbers, the comparison is not the usual number comparison. See the examples below:

I hope this helped. I am struggling to find if this kind of comparison is a known type of it and solutions that I can use already exist.

If I'm not doing a good job of explaining it properly, do not hesitate to let me know. I am happy to provide more examples

Edit In case someone has a similar problem, I found RangeTree to store the high-low values and compare incoming data.


Solution

  • This is a main program for a .NET console app that uses default .NET string comparison on your test data:

    internal class Program
    {
        static void Main(string[] args)
        {
            var lo = "9958";
            var hi = "99585";
            var strings = new List<string>{ "9958", "99581", "99585" };
            CheckIt(lo, hi, strings);
    
            lo = "30789";
            hi = "310100";
            strings = new List<string>{ "30789", "30790", "31000" };
            CheckIt(lo, hi, strings);
            
            lo = "81190";
            hi = "81190ZZ";
            strings = new List<string>{ "81190", "81190A", "81190AA", "81190B", "81190C", "81190AB", "81190ZZ" };
            CheckIt(lo, hi, strings);
        }
    
        static void CheckIt(string lo, string hi, List<string> strings)
        {
            foreach(var s in strings)
            {
                Console.WriteLine($"{s} >= {lo} <= {hi}: {s.CompareTo(lo) >= 0 && s.CompareTo(hi) <= 0}");
            }
        }
    }
    

    All outputs are True. Of course you could write better test code and perhaps use a unit test approach but this is a simple example to get you started.

    Note: although it may seem like a trivial topic, I hope sorting strings is a thing I hope all developers have pondered and explored for a few hours at some point in their learning. For instance, you should know why "1" could sort before "10" when sorted as a string, or whether "a" comes before "A". Once you understand this well enough, many other things start to makes sense (and other good questions comes to mind, such as does a with an accent in spanish come before a without an accent ... ?)