Reputation: 1068
I have a string that looks like this:
3x3x3x204x4x4x6f
I want to read these letters in a row and want to count the amount of times I see the same pattern. For instance, I see that 3x happens 3 times. I want my counter to then reset and start from the position it ended on and if it sees a pattern again like the one above, give me count of repetitions.
I have tried this with no luck (I'm reading 2 characters at a time):
foreach (var set in splitString)
{
currChars = set;
if (!currChars.Contains(prevChars))
{
if (!currChars.Contains(_prevchars))
{
}
newSet.Add(_prevchar);
newSet.Add(occurrenceCount.ToString());
newSet.Add("x");
occurrenceCount = 0;
newSet.Add(currChars);
}
else
{
occurrenceCount = occurrenceCount + 2;
_prevchar = MethodX.StringManipulation.TruncateLongString(prevChars, 1);
_prevchars = currChars;
}
prevChars = currChars;
}
Upvotes: 1
Views: 159
Reputation: 32797
var repeatList=Regex.Matches(input,@"(.+)(\1)+")
.Cast<Match>()
.Select(x=>
new {
name = x.Groups[1].Value,
count = x.Groups[2].Captures.Cast<Capture>().Count()+1
}
);
You can now iterate
foreach(var repeat in repeatList)
{
repeat.name;
repeat.count;
}
Upvotes: 0
Reputation: 21917
Without using Regex, you can use the overload of String.IndexOf
which accepts a starting position parameter. For every ocurrence of the pattern you find, increment the position accordingly and search again.
string s = "3x3x3x204x4x4x6f";
string pattern = "3x";
int count = 0;
int pos = 0;
while (true)
{
int index = s.IndexOf(pattern, pos);
if (index == -1) break;
count++;
pos = index + pattern.Length;
}
//count == 3
Upvotes: 2