Split string after certain character count

二次信任 提交于 2019-11-28 12:50:21

Following example splits 10 characters per line, you can change as you like {N} where N can be any number.

var input = "stacktraceabcdefghijklmnopqrstuvwxyztacktraceabcdefghijklmnopqrswxyztacktraceabcdefghijk";
var regex = new Regex(@".{10}");
string result = regex.Replace(input, "$&" + Environment.NewLine);
Console.WriteLine(result);

Here is the Demo

you can use the following code:

string yourstring;

StringBuilder sb = new StringBuilder();

for(int i=0;i<yourstring.length;++i){
if(i%100==0){
sb.AppendLine();
}
sb.Append(yourstring[i]);
}

you may create a function for this

    string splitat(string line, int charcount)
{
     string toren = "";
     if (charcount>=line.Length)
     {
          return line;
     }
     int totalchars = line.Length;
     int loopcnt = totalchars / charcount;
     int appended = 0;
     for (int i = 0; i < loopcnt; i++)
     {
          toren += line.Substring(appended, charcount) + Environment.NewLine;
          appended += charcount;
          int left = totalchars - appended;
          if (left>0)
          {
               if (left>charcount)
               {
                    continue;
               }
               else
               {
                    toren += line.Substring(appended, left) + Environment.NewLine;
               }
          }
     }
     return toren;
}

Best , Easiest and Generic Answer :). Just set the value of splitAt to the that number of character count after that u want it to break.

string originalString = "1111222233334444";
List<string> test = new List<string>();
int splitAt = 4; // change 4 with the size of strings you want.
for (int i = 0; i < originalString.Length; i = i + splitAt)
{
    if (originalString.Length - i >= splitAt)
        test.Add(originalString.Substring(i, splitAt));
    else
        test.Add(originalString.Substring(i,((originalString.Length - i))));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!