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.

+3


source to share


5 answers


This worked for me:



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

      

+11


source


Simple for classic holes:



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

      

+5


source


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:

http://msdn.microsoft.com/en-us/library/6f7hht7k.aspx

http://msdn.microsoft.com/en-us/library/az24scfc.aspx

+2


source


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!

+1


source


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

      

+1


source







All Articles