简体   繁体   English

检查字符串是否仅包含一种类型的字母 C#

[英]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我希望它检测字符串是否只包含那个字母,所以 output 应该是这样的

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:您可以像这样使用 function:

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匹配字符串 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,第一个字符是 Unicode 字母(一个字符 class 涵盖许多字符,而不仅仅是 ASCII 字符 AZ 和 aZ),然后是,

  • 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.所以空字符串会通过测试,“aaaaaaAaaa”也会失败,但“aaaaaaa”会通过测试。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM