Search code examples
c#stringgroupingstring-formatting

Add separator to string at every N characters?


I have a string which contains binary digits. How to separate string after each 8 digit?

Suppose the string is:

string x = "111111110000000011111111000000001111111100000000";

I want to add a separator like ,(comma) after each 8 character.

output should be :

"11111111,00000000,11111111,00000000,11111111,00000000,"

Then I want to send it to a list<> last 8 char 1st then the previous 8 chars(excepting ,) and so on.

How can I do this?


Solution

  • Regex.Replace(myString, ".{8}", "$0,");
    

    If you want an array of eight-character strings, then the following is probably easier:

    Regex.Split(myString, "(?<=^(.{8})+)");
    

    which will split the string only at points where a multiple of eight characters precede it.