代码之家  ›  专栏  ›  技术社区  ›  Conrad Frix

在不使用string.split()的c中拆分字符串的替代方法是什么?

  •  2
  • Conrad Frix  · 技术社区  · 15 年前

    我看到了这个 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. Regex建议(不执行)
    3. LINQ聚合法

    是这样吗?

    3 回复  |  直到 15 年前
        1
  •  9
  •   LukeH    15 年前

    写自己的东西相当简单 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
  •  2
  •   Guffa    15 年前

    你自己做一个循环来做分割。这是一个使用 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
  •  1
  •   Brad Cunningham    15 年前

    正则表达式?

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