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.

2
  • That is not how split works. Custom logic is required to select the 1s and 0s separate on a list of strings. Commented Jul 18, 2014 at 12:20
  • 1
    See: stackoverflow.com/questions/664194/… Commented Jul 18, 2014 at 12:28

2 Answers 2

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(',');
Sign up to request clarification or add additional context in comments.

2 Comments

+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...
@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.
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 Comments

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: Nice catch - it will save some memory and performance. Changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.