[英]How can i check of a string contains a letter space letter space and anotherl letter C#
[英]Check if string contains only one type of letter C#
例如,我想了解如何检测字符串是否仅包含一种类型的字母
输入:
......
我希望它检测字符串是否只包含那个字母,所以 output 应该是这样的
String contains only one type of letter
尝试这个:
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;
}
您可以像这样使用 function:
bool containsOneLetter = ContainsOnlyOneLetter("...");
if (containsOneLetter == true)
{
//Put code here when the letters are the same...
}
else
{
//Code when there are different letters..
}
这个正则表达式
^(\p{L})(\1)*$
匹配字符串 where
第一个字符是 Unicode 字母(一个字符 class 涵盖许多字符,而不仅仅是 ASCII 字符 AZ 和 aZ),然后是,
_与第一组匹配的完全相同的字符零次或多次重复
所以空字符串会通过测试,“aaaaaaAaaa”也会失败,但“aaaaaaa”会通过测试。
但为什么?
这可以说比上面的正则表达式更简单,而且几乎可以肯定更快:
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.