Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check repeated letters in a string c#

I am creating a program that checks repeated letters in a string.

For Example:

wooooooooooow
happpppppppy

This is my code:

 string repeatedWord = "woooooooow";
 for (int i = 0; i < repeatedWord.Count(); i++)
 {
     if (repeatedWord[i] == repeatedWord[i+1])
     {
          // ....
     }
 }

The code works but it will always have an error because the last character [i + 1] is empty/null.

The error is Index was outside the bounds of the array.

Any solution for this?

like image 357
MMakati Avatar asked Aug 08 '13 18:08

MMakati


2 Answers

run the loop until repeatedWord.Count()-1

like image 127
Abdullah Shoaib Avatar answered Sep 22 '22 12:09

Abdullah Shoaib


Regular Expression:

Regex rxContainsMultipleChars = new Regex( @"(?<char>.)\k<char>" , RegexOptions.ExplicitCapture|RegexOptions.Singleline ) ;
.
.
.
string myString = SomeStringValue() ;
bool containsDuplicates = rxDupes.Match(myString) ;

or Linq

string s = SomeStringValue() ;
bool containsDuplicates = s.Where( (c,i) => i > 0 && c == s[i-1] )
                           .Cast<char?>()
                           .FirstOrDefault() != null
                           ;

or roll yer own:

public bool ContainsDuplicateChars( string s )
{
  if ( string.IsNullOrEmpty(s) ) return false ;

  bool containsDupes = false ;
  for ( int i = 1 ; i < s.Length && !containsDupes ; ++i )
  {
    containsDupes = s[i] == s[i-1] ;
  }

  return containsDupes ;
}

Or even

public static class EnumerableHelpers
{
  public static IEnumerable<Tuple<char,int>> RunLengthEncoder( this IEnumerable<char> list )
  {
    char? prev  = null ;
    int   count = 0 ;

    foreach ( char curr in list )
    {
      if      ( prev == null ) { ++count ; prev = curr ; }
      else if ( prev == curr ) { ++count ;               }
      else if ( curr != prev )
      {
        yield return new Tuple<char, int>((char)prev,count) ;
        prev = curr ;
        count = 1 ;
      }
    }
  }
}

With this last one...

bool hasDupes = s.RunLengthEncoder().FirstOrDefault( x => x.Item2 > 1 ) != null ;

or

foreach (Tuple<char,int> run in myString.RunLengthEncoder() )
{
  if ( run.Item2 > 1 )
  {
     // do something with the run of repeated chars.
  }
}
like image 43
Nicholas Carey Avatar answered Sep 19 '22 12:09

Nicholas Carey