Split string after certain character count

前端 未结 4 1266
刺人心
刺人心 2020-12-11 07:25

I need some help. I\'m writing an error log using text file with exception details. With that I want my stack trace details to be written like the below and not in straight

相关标签:
4条回答
  • 2020-12-11 07:51

    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]);
    }
    
    0 讨论(0)
  • 2020-12-11 07:54

    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

    0 讨论(0)
  • 2020-12-11 08:02

    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;
    }
    
    0 讨论(0)
  • 2020-12-11 08:09

    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))));
    }
    
    0 讨论(0)
提交回复
热议问题