在x个新行之后拆分字符串

时间:2015-10-07 14:08:11

标签: .net regex string split

我还没有在.net网上找到解决方案。

我需要能够将大约42,000行的字符串分成每行5000行的单个字符串。

String的格式为

"some stuff\d\nsome things\d\n..."

重复约42,000次。所以现实地我需要9个字符串,8个将包含5000 \ d \ n,一个将包含2000.但它需要在一般情况下工作。

因此字符串需要在每5000秒\ d \ n时被破坏并保存为单独的字符串。

1 个答案:

答案 0 :(得分:0)

编辑以下说明:一旦您在每个\d\n上拆分了长字符串,就可以使用这种通用扩展方法将字符串批处理为5000批次,最后一批中剩余任何剩余字符串:

string[] longList = reallyLongString
                   .Split(new string[] { "\d\n" }, StringSplitOptions.None);

var batchesOfStrings = longList.Batch(5000);

foreach (var batch in batchesOfStrings)
{
   … 
}

扩展方法(必须在静态类中):

public static IEnumerable<IList<T>> Batch<T>(this IEnumerable<T> source, int batchSize)
{
    var batch = new List<T>(batchSize);

    foreach (var item in source)
    {
        batch.Add(item);
        if (batch.Count == batchSize)
        {
            yield return batch;
            batch = new List<T>(batchSize);
        }
    }

    if (batch.Any())
    {
        yield return batch;
    }
}