Home > database >  Check if characters in String are in alphabetical order
Check if characters in String are in alphabetical order

Time:12-14

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 "abc" but words like "aPple" 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));
    }

CodePudding user response:

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;
}

or linq variant ( I am not sure what is faster)

public static bool IsAlphabetical(string s, bool checkWithoutCase=true, bool checkWithCase=true)
{
    var equal=false;
    
    if (checkWithCase) equal= s.OrderBy(x => x).SequenceEqual(s);
    
    // check without case
    if (!equal && checkWithoutCase)
    {
      s=s.ToLower();
     equal = s.OrderBy(x => x).SequenceEqual(s);
    }
    
    return equal;
}
  • Related