Splitting a string into chunks of a certain size

后端 未结 30 1606
时光说笑
时光说笑 2020-11-22 07:55

Suppose I had a string:

string str = \"1111222233334444\"; 

How can I break this string into chunks of some size?

e.g., breaking t

30条回答
  •  礼貌的吻别
    2020-11-22 08:26

    List SplitString(int chunk, string input)
    {
        List list = new List();
        int cycles = input.Length / chunk;
    
        if (input.Length % chunk != 0)
            cycles++;
    
        for (int i = 0; i < cycles; i++)
        {
            try
            {
                list.Add(input.Substring(i * chunk, chunk));
            }
            catch
            {
                list.Add(input.Substring(i * chunk));
            }
        }
        return list;
    }
    

提交回复
热议问题