什么是斯普利特在C#中的字符串不使用String.Split的替代品() [英] What are the alternatives to Split a string in c# that don't use String.Split()

查看:128
本文介绍了什么是斯普利特在C#中的字符串不使用String.Split的替代品()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到要求给出一个字符串,这个问题史密斯;罗杰斯; McCalne你怎么可以产生一个集合。这个问题的答案是使用String.Split。

I saw this question that asks given a string "smith;rodgers;McCalne" how can you produce a collection. The answer to this was to use String.Split.

如果我们没有分裂()建于你该怎么办呢?

If we don't have Split() built in what do you do instead?

更新:

我承认写一个分裂的功能是相当容易的。下面是我会一直写。 。通过使用的IndexOf和提取使用的子字符串中的字符串循环

I admit writing a split function is fairly easy. Below is what I would've wrote. Loop through the string using IndexOf and extract using Substring.

string s = "smith;rodgers;McCalne";

string seperator = ";";
int currentPosition = 0;
int lastPosition = 0;

List<string> values = new List<string>();

do
{
    currentPosition = s.IndexOf(seperator, currentPosition + 1);
    if (currentPosition == -1)
        currentPosition = s.Length;

    values.Add(s.Substring(lastPosition, currentPosition - lastPosition));

    lastPosition = currentPosition+1;

} while (currentPosition < s.Length);



我把在SSCLI实施偷看其类似于上面的,除了它处理方法更多的使用案例和它使用一个不安全的方法操作的子串的提取之前,确定分离器的索引。

I took a peek at SSCLI implementation and its similar to the above except it handles way more use cases and it uses an unsafe method to determine the indexes of the separators before doing the substring extraction.

其他建议如下。


  1. 使用迭代器的扩展方法阻止

  2. 正则表达式的建议(不执行)

  3. LINQ的聚合方法

这是它?

推荐答案

这是相当简单的写你自己的拆分等价的。

It's reasonably simple to write your own Split equivalent.

下面是一个简单的例子,但在现实中你可能希望有更多的灵活性创造了一些重载。 (好吧,在现实的你只是用框架内置的拆分方法!)

Here's a quick example, although in reality you'd probably want to create some overloads for more flexibility. (Well, in reality you'd just use the framework's built-in Split methods!)

string foo = "smith;rodgers;McCalne";
foreach (string bar in foo.Split2(";"))
{
    Console.WriteLine(bar);
}

// ...

public static class StringExtensions
{
    public static IEnumerable<string> Split2(this string source, string delim)
    {
        // argument null checking etc omitted for brevity

        int oldIndex = 0, newIndex;
        while ((newIndex = source.IndexOf(delim, oldIndex)) != -1)
        {
            yield return source.Substring(oldIndex, newIndex - oldIndex);
            oldIndex = newIndex + delim.Length;
        }
        yield return source.Substring(oldIndex);
    }
}

这篇关于什么是斯普利特在C#中的字符串不使用String.Split的替代品()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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