Add separator to string at every N characters?

后端 未结 13 2291
半阙折子戏
半阙折子戏 2020-11-27 13:20

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

Suppose the string is:

string x = \"111111110000000011111111         


        
13条回答
  •  无人及你
    2020-11-27 13:34

    A little late to the party, but here's a simplified LINQ expression to break an input string x into groups of n separated by another string sep:

    string sep = ",";
    int n = 8;
    string result = String.Join(sep, x.InSetsOf(n).Select(g => new String(g.ToArray())));
    

    A quick rundown of what's happening here:

    • x is being treated as an IEnumberable, which is where the InSetsOf extension method comes in.
    • InSetsOf(n) groups characters into an IEnumerable of IEnumerable -- each entry in the outer grouping contains an inner group of n characters.
    • Inside the Select method, each group of n characters is turned back into a string by using the String() constructor that takes an array of chars.
    • The result of Select is now an IEnumerable, which is passed into String.Join to interleave the sep string, just like any other example.

提交回复
热议问题