简体   繁体   中英

How to split a string in chunks of eight chars?

I have following binary string

string binaryString = "110011100110011011001110011001101100111001100110110011100110011011001110001001100110011011001110";

Now I want to split the above string into group of 8 characters. eg.

11001110 11001110 11001110 11001110 11001110 11001110 

I tried following code but not getting expected result

var binary = binaryString.Where((x, y) => y % 8 == 0).ToList();

Try this:

IEnumerable<string> groups =  Enumerable.Range(0, binaryString.Length / 8)
                                        .Select(i => binaryString.Substring(i * 8, 8));

How about like?

string binaryString = "110011100110011011001110011001101100111001100110110011100110011011001110001001100110011011001110";
int step = binaryString.Length / 8;
for (int i = 0; i < step; i++)
{
    Console.WriteLine(binaryString.Substring(i, 8));
}

Output will be;

11001110
10011100
00111001
01110011
11100110
11001100
10011001
00110011
01100110
11001101
10011011
00110110

Here a DEMO .

List<string> bytes = binaryString.Select((c, i) => new { c, i })
                        .GroupBy(x => x.i / 8)
                        .Select(x => String.Join("",x.Select(y => y.c)))
                        .ToList();

In pure LINQ it's something like this:

var parts = Enumerable.Range(0, (binaryString.Length + 7) / 8)
                      .Select(p => binaryString.Substring(p * 8, Math.Min(8, binaryString.Length - (p * 8))))
                      .ToArray();

It's quite complex because it's able to "parse" ranges smaller than 8 characters. So:

string binaryString = "123456781234567" 

will return 12345678, 1234567

(binaryString.Length + 7) / 8)

This is the number of parts we will have. We have to round up clearly, so "0" is a part, and "123456781" are two parts. By adding (divisor - 1) we are rounding up.

Enumerable.Range(0, (binaryString.Length + 7) / 8)

This will give a sequence of numbers 0, 1, 2, # of parts - 1

.Select(p => 

The select :-)

binaryString.Substring(p * 8, Math.Min(8, binaryString.Length - (p * 8))))

The Substring

p * 8

The starting point, the part number * 8, (so part #0 starts at 0, part #1 starts at 8...)

Math.Min(8, binaryString.Length - (p * 8)))

Normally it would be 8, but the last part could be shorter. It means the Min between 8 and the number of remaining characters.

With a Regex it's perhaps easier:

var parts2 = Regex.Matches(binaryString, ".{1,8}")
                  .OfType<Match>()
                  .Select(p => p.ToString())
                  .ToArray();

(captures groups of 1-8 characters, any character, then take the matches and put them in an array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM