Home > Software design >  Best way to compare two strings when one is not an exact reverse of the other C#
Best way to compare two strings when one is not an exact reverse of the other C#

Time:12-30

So I have 2 string first is RJPDLLDHLDHAFASR and the second one is ASRAFLDHLDHDLRJP.

What could be the best way of comparing these two?

If one segregates this string into sub-strings then it can be observed how these 2 strings are similar. Sub strings RJP DL LDH LDH AF ASR.

That's true that I need a pattern where I should find above mentioned sub strings as a string in both the bigger strings.

CodePudding user response:

So I gave this a try on my lunch break. I used the rotation method I mentioned in the comments. This seems to work but there's probably room for improvement.

// Rotate a string 1 character to the right
// ex: "abc" -> "cba"
static string RotateRight(string s)
{
    return s[s.Length - 1]   s.Substring(0, s.Length - 1);
}

// Compare 2 strings using first n letters
static bool StrNCmp(string s1, string s2, int n)
{
    if (n == 0 || n > s1.Length || n > s1.Length) return false;
    return s1.Substring(0, n) == s2.Substring(0, n);
}

// Rotate s2 until a match with s1 is found.
// Return number of rotations or -1 if no match found
static int FindMatch(string s1, ref string s2)
{
    var count = 0;
    while (!StrNCmp(s1, s2, count))
    {
        s2 = RotateRight(s2);
        count  = 1;
        // Gone all the way around - stop
        if (count > s2.Length) return -1;
    }
    return count;
}

static void Main(string[] args)
{
    var s1 = "RJPDLLDHLDHAFASR";
    var s2 = "ASRAFLDHLDHDLRJP";
    while (s1.Length != 0)
    {
        var count = FindMatch(s1, ref s2);
        if (count == -1)
        {
            Console.WriteLine("FAIL");
            break;
        }
        Console.WriteLine(s1.Substring(0, count));
        // Remove matched chars
        s1 = s1.Substring(count);
        s2 = s2.Substring(count);
    }
}

Output:

RJP
DL
LDH
LDH
AF
ASR

CodePudding user response:

Take first letter in the first string. Iterate second string from the start, searching for this letter. When you find it try to match the substring made in the second string from that letter to the end with the substring of the same length in the first string. If they match remove the substrings and repeat the process. If you get two empty strings then the original strings are matched by this "reverse substring" criteria.

CodePudding user response:

You could use OrderBy for that

string a = "RJPDLLDHLDHAFASR";
string b = "ASRAFLDHLDHDLRJP";

string aa = String.Concat(a.OrderBy(C => c));
string bb = String.Concat(b.OrderBy(c => c));

bool isSame = aa == bb;
  •  Tags:  
  • c#
  • Related