Add separator to string at every N characters?

后端 未结 13 2172
半阙折子戏
半阙折子戏 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:43

    Here my two little cents too. An implementation using StringBuilder:

            public static string AddChunkSeparator (string str, int chunk_len, char separator)
            {
                if (str == null || str.Length < chunk_len) {
                    return str;
                }
                StringBuilder builder = new StringBuilder();
                for (var index = 0; index < str.Length; index += chunk_len) {
                    builder.Append(str, index, chunk_len);
                    builder.Append(separator);
                }
                return builder.ToString();
            }
    

    You can call it like this:

    string data = "111111110000000011111111000000001111111100000000";
    string output = AddChunkSeparator(data, 8, ',');
    
    0 讨论(0)
提交回复
热议问题