Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if characters in String are in alphabetical order

I’m supposed to take in a string and return true if it is in alphabetical order. So far in my solution I am able to get true from "biopsy" but words like "BeRrY" throw a false. I am assuming this is because some of the characters are capitalized but I don’t know where I am going wrong. This is what I have.

public bool IsAlphabetical(string s)
    {
        char[] c = s.ToCharArray();
        Array.Sort(c);
        return (c.SequenceEqual(s));
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if you need not case-sensitive comparison, you can try this

public static bool IsAlphabetical(string s,bool checkWithoutCase=true)
{
    var c = s.ToCharArray();
    Array.Sort(c);
    var equal = c.SequenceEqual(s);

    // check without case
    if (!equal && checkWithoutCase)
    {
        s = s.ToLower();
        Array.Sort(c = s.ToCharArray());
        equal = c.SequenceEqual(s);
    }
    return equal;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading