Reputation: 33
String value
String value = "11100110100";
I want to split it like shown below,
111,00,11,0,1,00
I tried that by splitting based on the numbers, as shown below:
List<string> result1= value.Split('0').ToList<string>();
List<string> result2= value.Split('1').ToList<string>();
It did not work so, how can i get the desired output (shown below) by splitting 1 and 0?
111
00
11
0
1
00
Thanks.
Upvotes: 3
Views: 238
Reputation:
Here is my extension method, without replacing - only parsing.
public static IEnumerable<string> Group(this string s)
{
if (s == null) throw new ArgumentNullException("s");
var index = 0;
while (index < s.Length)
{
var currentGroupChar = s[index];
int groupSize = 1;
while (index + 1 < s.Length && currentGroupChar == s[index + 1])
{
groupSize += 1;
index += 1;
}
index += 1;
yield return new string(currentGroupChar, groupSize);
}
}
Note: it works for every char grouping (not only 0 and 1)
Upvotes: 3
Reputation: 700800
You can put a character between each change from 0 to 1 and from 1 to 0, and split on that:
string[] result = value.Replace("10", "1,0").Replace("01", "0,1").Split(',');
Upvotes: 12