正则表达式:
Regex rxContainsMultipleChars = new Regex( @"(?<char>.)\k<char>" , RegexOptions.ExplicitCapture|RegexOptions.Singleline ) ;
.
.
.
string myString = SomeStringValue() ;
bool containsDuplicates = rxDupes.Match(myString) ;
或 Linq
string s = SomeStringValue() ;
bool containsDuplicates = s.Where( (c,i) => i > 0 && c == s[i-1] )
.Cast<char?>()
.FirstOrDefault() != null
;
或自己动手:
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 ;
}
甚至
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 ;
}
}
}
}
有了这最后一个...
bool hasDupes = s.RunLengthEncoder().FirstOrDefault( x => x.Item2 > 1 ) != null ;
或者
foreach (Tuple<char,int> run in myString.RunLengthEncoder() )
{
if ( run.Item2 > 1 )
{
// do something with the run of repeated chars.
}
}