简体   繁体   中英

Check whether two strings contain same words but in different order

I need a way to check two strings to see if they have the same words in them but in different positions. I only need the number of words out of word, not the actual words. For example: string 1 is "this is an out of order test" and string 2 is "this is an order out of test" would return 1 as one word is out of order.

I've started with the following code:

public int OutOfOrder(string string1, string string2)
{
    var search1 = string1.Split(' ');
    var search2 = string2.Split(' ');
    var OutOfOrder = 0;

    for (int i = 0; i < search1.Count() - 1; i++)
    {
        if (search2.Contains(search1[i]))
        {
            for (int j=0; j < search2.Count()-1; j++)
            {
                if(search1[i] == search2[j] && i == j)
                {
                    continue;
                }
                else if (search1[i] == search2[j] && i != j)
                {
                    OutOfOrder++;
                    break;
                }
            }
        }
    }

    return OutOfOrder;
}

However everything is out of order after the first one encountered and the number returned is not correct.

This does it

public static int OutOfOrder(string a, string b){

            //not out of order issuex`
        if (a.Length != b.Length) return -1;

        foreach(string str in a.Split(' ')){
            //not out of order issue
            if (!b.Contains(str)) return -1;
        }

        //if out of order issue...

        int count=0;

        string[] awords = a.Split(' ');
        string[] bwords = b.Split(' ');

        for(int i=0; i<bwords.Length; i++){
            if (!awords[i].Equals(bwords[i])) count++;
        }

        return (int)Math.Ceiling(0.0f + count/2);
        //if one is out of order, then it's expected it renders another out of order too.
        //so we need to divide it by 2 to get the one disturbing.
        //and ceiling is used to help for odd number of words
    }

Testing it now

public static void Main(string[] args)
{
    string a = "This solves the problem";
    string b = "This solves problem the";

    Console.WriteLine(OutOfOrder(a, b));
}

It outputs 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM