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?
run the loop until repeatedWord.Count()-1
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With