Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 597
Abdur Rahim Avatar asked Mar 29 '12 19:03

Abdur Rahim


People also ask

How to split a string every n characters java?

Using the String#substring Method Another way to split a String object at every nth character is to use the substring method. As shown above, the substring method allows us to get the part of the string between the current index i and i+n.

How can I insert a character after every n characters in Javascript?

To insert a character after every N characters, call the replace() method on the string, passing it the following regular expression - str. replace(/. {2}/g, '$&c') . The replace method will replace every 2 characters with the characters plus the provided replacement.


1 Answers

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.

like image 144
Joey Avatar answered Oct 04 '22 16:10

Joey