How to check if a string has more than two repeating characters
I am trying to check if a string contains more than two duplicate characters.
eg
'aabcd123' = ok
'aaabcd123' = not ok
'aabbab11!@' = ok
'aabbbac123!' = not ok
I tried something like this but no luck
if (string.Distinct().Count() > 2){
//do something
}
any help would be appreciated.
source to share
You can use Regex for this:
return Regex.IsMatch(inputString, @"(.)\1{2,}", RegexOptions.IgnoreCase)
This checks for any character, then at least 2x the same character. Works even with strings like "AaA" and can be modified to find out exactly what these characters are, where they appear in the string, and much more (also allows you to replace these substrings with something else)
Additional Information:
source to share
Since you want to find runs of three characters, not just three characters in a string, you need to scroll and look at three consecutive characters to see if they match. This loop will work.
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;
}
}
I would stick with this in the method and make the variables better and you're good to go!
source to share
[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;
}
source to share