C#: Cleanest way to divide a string array into N instances N items long

后端 未结 8 1393
我寻月下人不归
我寻月下人不归 2020-12-23 10:40

I know how to do this in an ugly way, but am wondering if there is a more elegant and succinct method.

I have a string array of e-mail addresses. Assume the string

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 11:06

    I think this is simple and fast enough.The example below divides the long sentence into 15 parts,but you can pass batch size as parameter to make it dynamic.Here I simply divide using "/n".

     private static string Concatenated(string longsentence)
     {
         const int batchSize = 15;
         string concatanated = "";
         int chanks = longsentence.Length / batchSize;
         int currentIndex = 0;
         while (chanks > 0)
         {
             var sub = longsentence.Substring(currentIndex, batchSize);
             concatanated += sub + "/n";
             chanks -= 1;
             currentIndex += batchSize;
         }
         if (currentIndex < longsentence.Length)
         {
             int start = currentIndex;
             var finalsub = longsentence.Substring(start);
             concatanated += finalsub;
         }
         return concatanated;
     }
    

    This show result of split operation.

     var parts = Concatenated(longsentence).Split(new string[] { "/n" }, StringSplitOptions.None);
    

提交回复
热议问题