首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在c#中拆分不使用String.Split()的字符串的替代方法是什么?

在c#中拆分不使用String.Split()的字符串的替代方法是什么?
EN

Stack Overflow用户
提问于 2010-08-27 22:18:38
回答 3查看 6K关注 0票数 3

我看到了这个question,它询问给定一个字符串"smith;rodgers;McCalne“,您如何生成一个集合。解决这个问题的方法是使用String.Split。

如果我们没有内置Split(),那么您应该做什么呢?

更新:

我承认编写拆分函数相当容易。下面是我会写的。使用IndexOf循环字符串,使用子字符串提取字符串。

代码语言:javascript
复制
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实现及其类似于上面的实现,除了它处理更多用例之外,它在进行子字符串提取之前使用一种不安全的方法来确定分隔符的索引。

其他人建议如下。

implementation)

  • Linq

  • 使用Iterator块

  • Regex建议的扩展方法(无

  • 聚合方法

)

是这个吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-08-27 22:53:30

编写自己的Split等价物相当简单。

下面是一个简单的例子,尽管实际上您可能希望创建一些重载以获得更大的灵活性。(实际上,您只需要使用框架的内置Split方法!)

代码语言:javascript
复制
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);
    }
}
票数 10
EN

Stack Overflow用户

发布于 2010-08-27 23:15:20

你做你自己的循环来做分裂。下面是一个使用Aggregate扩展方法的方法。效率不高,因为它在字符串上使用了+=运算符,因此它实际上不应该用作示例,但它可以:

代码语言:javascript
复制
string names = "smith;rodgers;McCalne";

List<string> split = names.Aggregate(new string[] { string.Empty }.ToList(), (s, c) => {
  if (c == ';') s.Add(string.Empty); else s[s.Count - 1] += c;
  return s;
});
票数 3
EN

Stack Overflow用户

发布于 2010-08-27 22:22:33

雷吉斯?

或者只是子字符串。这就是斯普利特在内部所做的

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3588503

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档