3

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.

Nahuel Ianni
  • 3,177
  • 4
  • 23
  • 30
Ricky
  • 33
  • 3
  • That is not how split works. Custom logic is required to select the 1s and 0s separate on a list of strings. – Rodrigo Jul 18 '14 at 12:20
  • 1
    See: http://stackoverflow.com/questions/664194/how-can-i-find-repeated-characters-with-a-regex-in-java – Emond Jul 18 '14 at 12:28

2 Answers2

12

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(',');
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • +1 for simplicity, in fact answer was hidden in question. " I want to split it like 111,00,11,0,1,00", just needed to find a way to put those commas in proper place. beautiful... – ahsant Jul 18 '14 at 12:37
  • @pwas: This is naturally not the most efficient way possible, but appropriate for the task as the desired return value is not an efficient way to represent the result. More efficient would be to just return an array with the length of each string, as the content of the strings is known. – Guffa Jul 18 '14 at 12:54
3

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)

  • 2
    Nice idea. You don't need to use a `StringBuilder` to build a string with the same character repeated. Just count the characters, and use `new String(lastchar, cnt)` to create a string to return. – Guffa Jul 18 '14 at 12:25
  • @Guffa: Nice catch - it will save some memory and performance. Changed. –  Jul 18 '14 at 12:30