Add separator to string at every N characters?

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

    ...or old school:

    public static List splitter(string in, out string csv)
    {
         if (in.length % 8 != 0) throw new ArgumentException("in");
         var lst = new List(in/8);
    
         for (int i=0; i < in.length / 8; i++) lst.Add(in.Substring(i*8,8));
    
         csv = string.Join(",", lst); //This we want in input order (I believe)
         lst.Reverse(); //As we want list in reverse order (I believe)
    
         return lst;
    }
    

提交回复
热议问题