简体   繁体   中英

Check if string contains only one type of letter C#

I want to find out how I could detect if a string contains only one type of letter for example

Input:

......

I want it to detect if the string contains only that letter, so the output should be something like this

String contains only one type of letter

Try this:

private bool ContainsOnlyOneLetter(string String)
    {
        if(String.Length == 0)
        {
            return true;
        }
        for(int i = 0; i < String.Length;i++)
        {
            if(String.Substring(i,1) != String.Substring(0,1))
            {
                return false;
            }
        }
        return true;
    }

And you can use the function like this:

bool containsOneLetter = ContainsOnlyOneLetter("...");

        if (containsOneLetter == true)
        {
            //Put code here when the letters are the same...
        }
        else
        {
            //Code when there are different letters..
        }

This regular expression

^(\p{L})(\1)*$

matches strings where

  • The 1st character is a Unicode Letter (a character class covering many, many more characters than just the ASCII characters AZ and aZ), followed by,

  • Zero or more repetitions of _the exact same character matched by the first group

So the empty string would fail the test, as would "aaaaaAaaa", but "aaaaaaa" would pass the test.

But... why?

This is arguably simpler, and almost certainly faster than the above regular expression:

public static bool isAllSameCharacter( string s )
{
  bool isValid = s != null && s.length > 0 && s[0].isLetter();
  char firstChar = s[0];

  for ( int i = 1 ; isValid && i < s.Length ; ++i )
  {
    isValid = s[i] == firstChar;
  }

  return isValid;
}

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