0

I want to change the sorting of strings so it is based off the following alphabet:

A,E,I,O,U,F,G,L,M,N,P,S,T,V,H,K,R

Instead of the standard A,B,C,D ... X,Y,Z

So I started to try and create a IComparer but stuck on how to implement.

Here is what I got so far which ain't much.

public class CustomSort : IComparer<string>
{
    public int Compare(string a, string b)
    {
        return 1;
    }
}

Any help would be much appreciated.

1
  • 1
    @xanatos It would appear SamoanProgrammer's instructor has done the former and SP is trying to do the latter. :roll: Commented Apr 11, 2017 at 12:28

1 Answer 1

3

It should be something very like this:

In the end you compare character by character, finding the "index" of the character inside a Order string. Perhaps to speed it up you could convert the Order string to a Dictionary<char, int> where the int is the "weight".

public class CustomSort : IComparer<string>
{
    public const string Order = "AEIOUFGLMNPSTVHKR";

    public int Compare(string a, string b)
    {
        if (a == null)
        {
            return b == null ? 0 : -1;
        }

        if (b == null)
        {
            return 1;
        }

        int minLength = Math.Min(a.Length, b.Length);

        for (int i = 0; i < minLength; i++)
        {
            int i1 = Order.IndexOf(a[i]);
            int i2 = Order.IndexOf(b[i]);

            if (i1 == -1)
            {
                throw new Exception(a);
            }

            if (i2 == -1)
            {
                throw new Exception(b);
            }

            int cmp = i1.CompareTo(i2);

            if (cmp != 0)
            {
                return cmp;
            }
        }

        return a.Length.CompareTo(b.Length);
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Hi xanatos, thank you very much. That has done exactly what I needed to do :) Awesome work mate!
So comparing "Hello There" to "HelloWorld" is going to thrown an exception, but comparing "Hello There" and "Hello" will not.
@juharr Yep :-) I don't do a correctness check on the whole string.
Actually both throw since you only deal with upper case characters. I guess as long as the strings only contain upper case A-Z this is good enough, but should be noted.
Yeah, I found I got an exception with lower case characters but I fixed that up and spaces, but the bulk of what I needed done was handled as I wanted :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.