每次回车后或125个字符后拆分字符串

时间:2014-06-02 14:37:12

标签: c#

假设我有一个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();
    }
}

1 个答案:

答案 0 :(得分:3)

喜欢什么?

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();