在每个回车或125个字符之后分割字符串

本文关键字:字符 之后 分割 字符串 125个 回车 | 更新日期: 2023-09-27 18:06:10

假设我有一个500字符长的字符串。我需要在每个回车和125个字符之后分割字符串。拆分后,我想将拆分后的字符串插入到一个有两列的表中:一列保存字符串,另一列保存星号(*),表示字符串是新行。

这是我到目前为止的代码。

class Program
{
    static void Main(string[] args)
    {
        string txt = "The lazy brown fox jumped over the fence. 'r'n" +
        "The lazy brown fox jumped over the fence." +
        " The lazy brown fox jumped over the fence. The lazy brown fox jumped over the fence. 'r'n" +
        "The lazy brown fox jumped over the fence. The lazy brown fox jumped over the fence. "+
        "The lazy brown fox jumped over the fence.The lazy brown fox jumped over the fence.";

        string[] items = SplitByLength(txt, 124);
        foreach (string item in items)
        {
            Console.WriteLine(item);
        }

    }
    private static string[] SplitByLength(string s, int split)
    {
        //Like using List because I can just add to it 
        List<string> list = new List<string>();
        // Integer Division
        int TimesThroughTheLoop = s.Length / split;

        for (int i = 0; i < TimesThroughTheLoop; i++)
        {
            list.Add(s.Substring(i * split, split));
        }
        // Pickup the end of the string
        if (TimesThroughTheLoop * split != s.Length)
        {
            list.Add(s.Substring(TimesThroughTheLoop * split));
        }
        return list.ToArray();
    }
}

在每个回车或125个字符之后分割字符串

像?

var lines = txt.Split("'r'n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
            .SelectMany(x => Regex.Matches(x, @".{0,125}('s+|$)")
                                  .Cast<Match>()
                                  .Select(m => m.Value).ToList())
            .ToList();