patterncsharpModerate
Checking if a text contains N consecutive repeating characters
Viewed 0 times
textrepeatingcheckingcontainscharactersconsecutive
Problem
I want to check a text for consecutive repeating characters. For example, with a minimum of 3 consecutive chars, this should match:
This should not match:
This is my code:
It works but I feel there should be a cleaner solution to this problem.
- Okeee
- OOOkee
- Alsoook
This should not match:
- No not okee, oh no
This is my code:
public static bool HasConsecutiveChars(string source, int sequenceLength)
{
if (string.IsNullOrEmpty(source))
{
return false;
}
if (source.Length == 1)
{
return false;
}
int charCount = 1;
for (int i = 0; i = sequenceLength)
{
return true;
}
}
else
{
charCount = 1;
}
}
return false;
}It works but I feel there should be a cleaner solution to this problem.
Solution
Edit - there is a bug with this: see my other answer
This is very easy with Regular Expressions:
The regular expression simply captures each letter into a group and then checks if it is repeated the number of times minus one. I've omitted range checking.
Talking about your code for a moment:
Great method name - would be perfect as an extension method in my opinion.
These two checks can be merged:
This is very easy with Regular Expressions:
public static bool HasConsecutiveChars(string source, int sequenceLength)
{
// should check sequence length
// just repeating letters
return Regex.IsMatch(source,"([a-zA-Z])\\1{"+ (sequenceLength - 1) + "}");
// any character version
// return Regex.IsMatch(source,"(.)\\1{"+ (sequenceLength - 1) + "}");
}The regular expression simply captures each letter into a group and then checks if it is repeated the number of times minus one. I've omitted range checking.
Talking about your code for a moment:
Great method name - would be perfect as an extension method in my opinion.
These two checks can be merged:
if (string.IsNullOrEmpty(source))
{
return false;
}
if (source.Length == 1)
{
return false;
}Code Snippets
public static bool HasConsecutiveChars(string source, int sequenceLength)
{
// should check sequence length
// just repeating letters
return Regex.IsMatch(source,"([a-zA-Z])\\1{"+ (sequenceLength - 1) + "}");
// any character version
// return Regex.IsMatch(source,"(.)\\1{"+ (sequenceLength - 1) + "}");
}if (string.IsNullOrEmpty(source))
{
return false;
}
if (source.Length == 1)
{
return false;
}Context
StackExchange Code Review Q#102568, answer score: 16
Revisions (0)
No revisions yet.