Search code examples
c#stringcomparecharacter

Comparing characters in a string in C#


I am trying to write a method that will determine whether a string that contains only letters is an isogram. (An isogram is a word that has no repeating letters, consecutive or non-consecutive.) Here's my code:

***static bool IsIsogram(string str)
{
    for (int i = 0; i <= str.Length; i++)
    {
        for (int j = 0; j < i; j++)
        {
            if (string.Compare("str[i]", "str[j]") == 0)
            {
                return false;
            }
            else if (string.Compare("str[i]", "str[j]") == 1)
            {
                return true;
            }
        }
    }

}

IsIsogram("Hello");***

EDIT: How about this:

static bool IsIsogram(string str) { 
   foreach (char c in str) { 
      for (int i = 0;i<=str.Length;i++) { 
         if (c == str[i]) { 
            return false; 
         } 
         else { 
            return true; 
         } 
      } 
   } 
} 
IsIsogram("Hello");

Solution

  • All you really want to do is check if there are any repeated characters after you set letters to capital/lower to compare.

    static bool IsIsogram(string str)
    {
        return str.ToLower().Distinct().Count() == str.Length;
    }