Home > database >  Check if string contains only one type of letter C#
Check if string contains only one type of letter C#

Time:02-05

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

CodePudding user response:

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

CodePudding user response:

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 A-Z and a-Z), 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;
}
  •  Tags:  
  • Related