如何检查字符串c#中的重复字母

MMa*_*ati 4 c# string if-statement

我正在创建一个程序来检查字符串中的重复字母.

例如:

wooooooooooow
happpppppppy

这是我的代码:

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

代码可以工作,但它总是会出错,因为最后一个字符[i + 1]是空的/ null.

错误是索引超出了数组的范围.

对此有何解决方案?

Abd*_*aib 10

运行循环直到 repeatedWord.Count()-1


Nic*_*rey 5

正则表达式:

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

或林克

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

或者自己动手:

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 ;
}
Run Code Online (Sandbox Code Playgroud)

甚至

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 ;
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

有了这最后一个...

bool hasDupes = s.RunLengthEncoder().FirstOrDefault( x => x.Item2 > 1 ) != null ;
Run Code Online (Sandbox Code Playgroud)

或者

foreach (Tuple<char,int> run in myString.RunLengthEncoder() )
{
  if ( run.Item2 > 1 )
  {
     // do something with the run of repeated chars.
  }
}
Run Code Online (Sandbox Code Playgroud)