C#中有一个懒惰的`String.Split`吗? [英] Is there a lazy `String.Split` in C#

查看:65
本文介绍了C#中有一个懒惰的`String.Split`吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有 string.Split 方法似乎返回字符串数组(string[]).

我想知道是否存在一个懒惰的变体,它返回一个IEnumerable<string>,使得对于大字符串(或无限长IEnumerable<char>)来说,当一个仅对第一个子序列感兴趣时,它会节省计算量,因为以及记忆.如果字符串是由设备/程序(网络,终端,管道)构成的,因此不需要立即完全使用整个字符串,这也可能很有用.这样,一个人就可以处理第一次出现的事情.

I'm wondering if there is a lazy variant that returns an IEnumerable<string> such that one for large strings (or an infinite length IEnumerable<char>), when one is only interested in a first subsequences, one saves computational effort as well as memory. It could also be useful if the string is constructed by a device/program (network, terminal, pipes) and the entire strings is thus not necessary immediately fully available. Such that one can already process the first occurences.

.NET框架中是否存在这种方法?

Is there such method in the .NET framework?

推荐答案

您可以轻松地编写一个:

You could easily write one:

public static class StringExtensions
{
    public static IEnumerable<string> Split(this string toSplit, params char[] splits)
    {
        if (string.IsNullOrEmpty(toSplit))
            yield break;

        StringBuilder sb = new StringBuilder();

        foreach (var c in toSplit)
        {
            if (splits.Contains(c))
            {
                yield return sb.ToString();
                sb.Clear();
            }
            else
            {
                sb.Append(c);
            }
        }

        if (sb.Length > 0)
            yield return sb.ToString();
    }
}

很明显,我尚未使用string.split对它进行奇偶校验测试,但我认为它应该可以正常工作.

Clearly, I haven't tested it for parity with string.split, but I believe it should work just about the same.

正如Servy所说,这不会在字符串上分开.这不是那么简单,也不是那么有效,但是基本上是相同的模式.

As Servy notes, this doesn't split on strings. That's not as simple, and not as efficient, but it's basically the same pattern.

public static IEnumerable<string> Split(this string toSplit, string[] separators)
{
    if (string.IsNullOrEmpty(toSplit))
        yield break;

    StringBuilder sb = new StringBuilder();
    foreach (var c in toSplit)
    {
        var s = sb.ToString();
        var sep = separators.FirstOrDefault(i => s.Contains(i));
        if (sep != null)
        {
            yield return s.Replace(sep, string.Empty);
            sb.Clear();
        }
        else
        {
            sb.Append(c);
        }
    }

    if (sb.Length > 0)
        yield return sb.ToString();
}

这篇关于C#中有一个懒惰的`String.Split`吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆