Add separator to string at every N characters?

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

    This is much faster without copying array (this version inserts space every 3 digits but you can adjust it to your needs)

    public string GetString(double valueField)
    {
        char[] ins = valueField.ToString().ToCharArray();
        int length = ins.Length + (ins.Length / 3);
        if (ins.Length % 3 == 0)
        {
            length--;
        }
        char[] outs = new char[length];
    
        int i = length - 1;
        int j = ins.Length - 1;
        int k = 0;
        do
        {
            if (k == 3)
            {
                outs[i--] = ' ';
                k = 0;
            }
            else
            {
                outs[i--] = ins[j--];
                k++;
            }           
        }
        while (i >= 0);
    
        return new string(outs);
    }
    
    0 讨论(0)
  • 2020-11-27 13:24
    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.

    0 讨论(0)
  • 2020-11-27 13:26

    For every 1 character, you could do this one-liner:

    string.Join(".", "1234".ToArray()) //result: 1.2.3.4
    
    0 讨论(0)
  • 2020-11-27 13:30

    ...or old school:

    public static List<string> splitter(string in, out string csv)
    {
         if (in.length % 8 != 0) throw new ArgumentException("in");
         var lst = new List<string>(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;
    }
    
    0 讨论(0)
  • 2020-11-27 13:30

    There's another Regex approach:

    var str = "111111110000000011111111000000001111111100000000";
    # for .NET 4
    var res = String.Join(",",Regex.Matches(str, @"\d{8}").Cast<Match>());
    
    # for .NET 3.5
    var res = String.Join(",", Regex.Matches(str, @"\d{8}")
                .OfType<Match>()
                .Select(m => m.Value).ToArray());
    
    0 讨论(0)
  • 2020-11-27 13:31

    Try this:

    var s = "111111110000000011111111000000001111111100000000";
    var list = Enumerable
        .Range(0, s.Length/8)
        .Select(i => s.Substring(i*8, 8));
    var res = string.Join(",", list);
    
    0 讨论(0)
提交回复
热议问题