【问题标题】:What are the alternatives to Split a string in c# that don't use String.Split()在不使用 String.Split() 的 c# 中拆分字符串的替代方法是什么
【发布时间】:2010-09-14 02:59:43
【问题描述】:

我看到了这个question,它询问给定一个字符串“smith;rodgers;McCalne”如何制作一个集合。答案是使用 String.Split。

如果我们没有内置 Split(),你会怎么做?

更新:

我承认编写拆分函数相当容易。下面是我会写的。使用 IndexOf 循环字符串并使用 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 的实现,它与上面的类似,除了它处理更多的用例,并且在提取子字符串之前使用不安全的方法来确定分隔符的索引。

其他人提出了以下建议。

  1. 使用迭代器块的扩展方法
  2. 正则表达式建议(未实施)
  3. Linq 聚合方法

是这个吗?

【问题讨论】:

  • 我不明白这个问题;答案不是“写一个拆分方法”吗?写起来一点也不难。

标签: c# string


【解决方案1】:

编写自己的 Split 等效项相当简单。

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

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

【讨论】:

    【解决方案2】:

    您创建自己的循环来进行拆分。这是使用Aggregate 扩展方法的一种。效率不是很高,因为它在字符串上使用了 += 运算符,所以它不应该被用作示例,但它确实有效:

    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】:

      正则表达式?

      或者只是子字符串。这就是Split在内部所做的

      【讨论】:

      • 哈哈,我认为OP本质上是在询问如何实现拆分方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 2012-05-24
      • 2018-07-27
      相关资源
      最近更新 更多