我将尝试检查一个字符串是否包含超过两个重复字符。
例如:
'aabcd123' = ok
'aaabcd123' = not ok
'aabbab11!@' = ok
'aabbbac123!' = not ok
我尝试过类似的方法,但没有成功。
if (string.Distinct().Count() > 2){
//do something
}
任何帮助都将不胜感激。
我将尝试检查一个字符串是否包含超过两个重复字符。
例如:
'aabcd123' = ok
'aaabcd123' = not ok
'aabbab11!@' = ok
'aabbbac123!' = not ok
if (string.Distinct().Count() > 2){
//do something
}
任何帮助都将不胜感激。
这个对我有效:
public bool IsOK(string s)
{
if(s.Length < 3) return true;
return !s.Where((c,i)=> i >= 2 && s[i-1] == c && s[i-2] == c).Any();
}
'aabcd123' : OK
'aaabcd123' : not OK
'aabbab11!@' : OK
'aabbbac123!' : not OK
Any
一旦找到匹配项就会停止向 Where
请求匹配,因此仅当没有匹配项时才会过滤整个集合。 - D Stanley只是为了经典循环而已:
public bool HasRepeatingChars(string str)
{
for(int i = 0; i < str.Length - 2; i++)
if(str[i] == str[i+1] && str[i] == str[i+2])
return true;
return false;
}
return Regex.IsMatch(inputString, @"(.)\1{2,}", RegexOptions.IgnoreCase)
这个代码用来检查任何字符,然后检查该字符至少出现了两次。即使是像"AaA"这样的字符串也可以运行,并且可以修改以精确查找这些字符在字符串中的位置等更多信息(还允许您替换这些子字符串为其他内容)。
更多信息:
既然您想在字符串中找到三个字符的连续运行而不仅仅是三个字符,那么您需要循环并查看三个连续字符是否相同。像这样的循环将起作用。
string myString = "aaabbcd";
bool hasMoreThanTwoRepeatingCharsInARow = false;
for(int index = 2; index < myString.Length; index++)
{
if(myString[index] == myString[index - 1] && myString[index] == myString[index - 2])
{
hasMoreThanTwoRepeatingCharsInARow = true;
}
}
[TestMethod]
public void Test()
{
const string sample1 = "aabcd123";
const string sample2 = "aaabcd123";
const string sample3 = "aabbab11!@";
const string sample4 = "aabbbac123!";
Assert.IsTrue(IsOk(sample1));
Assert.IsFalse(IsOk(sample2));
Assert.IsTrue(IsOk(sample3));
Assert.IsFalse(IsOk(sample4));
}
private bool IsOk(string str)
{
char? last = null;
var i = 1;
foreach (var c in str)
{
if (last == c)
{
i++;
if (i > 2) return false;
}
else
{
i = 1;
}
last = c;
}
return true;
}
(?:.*<letter>.*){2}
(?:.*b.*){2}
对于所有的元音字母
(?:.*[aeiou].*){2}
关于在C#中使用正则表达式,请参考https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=net-5.0
'aaabcd123'
不行?它确实包含超过两个重复字符。 - Cristian Lupascu