【问题标题】:Performing actions on a string using a StringBuilder使用 StringBuilder 对字符串执行操作
【发布时间】:2016-05-31 15:41:58
【问题描述】:

我正在编写一个C# 应用程序,该应用程序在string 调用的内容中追加、插入、替换和查找string 内容。多个名为 editObjects 的对象正在对同一个名为 string 的内容执行这些操作。

我目前正在将一个StringBuilder 对象传递给每个editObject 对象,然后每个editObjectStringBuilder 对象执行操作。

这个问题有两个部分:

我是否正确地说StringBuilder 是对string 执行多项操作的最有效方式?

我从 2013 年发现这篇帖子:Fastest search method in StringBuilder,并想知道是否有一些已知代码可以更有效地在 StringBuilder 中找到 string 的索引?

public static class StringBuilderSearching
{
  public static bool Contains(this StringBuilder haystack, string needle)
  {
    return haystack.IndexOf(needle) != -1;
  }
  public static int IndexOf(this StringBuilder haystack, string needle)
  {
    if(haystack == null || needle == null)
      throw new ArgumentNullException();
    if(needle.Length == 0)
      return 0;//empty strings are everywhere!
    if(needle.Length == 1)//can't beat just spinning through for it
    {
      char c = needle[0];
      for(int idx = 0; idx != haystack.Length; ++idx)
        if(haystack[idx] == c)
          return idx;
      return -1;
    }
    int m = 0;
    int i = 0;
    int[] T = KMPTable(needle);
    while(m + i < haystack.Length)
    {
      if(needle[i] == haystack[m + i])
      {
        if(i == needle.Length - 1)
          return m == needle.Length ? -1 : m;//match -1 = failure to find conventional in .NET
        ++i;
      }
      else
      {
        m = m + i - T[i];
        i = T[i] > -1 ? T[i] : 0;
      }
    }
    return -1;
  }      
  private static int[] KMPTable(string sought)
  {
    int[] table = new int[sought.Length];
    int pos = 2;
    int cnd = 0;
    table[0] = -1;
    table[1] = 0;
    while(pos < table.Length)
      if(sought[pos - 1] == sought[cnd])
        table[pos++] = ++cnd;
      else if(cnd > 0)
        cnd = table[cnd];
      else
        table[pos++] = 0;
    return table;
  }
}

【问题讨论】:

    标签: c# .net string search stringbuilder


    【解决方案1】:

    StringBuilder 更快 for most string manipulations - 这并不意味着它是最好的所有人 多个操作在@上完成987654326@.

    就您而言,您愿意在StringBuilder 中找到string,这需要您做以下两件事之一:

    • O(n) 处进行标准搜索,迭代整个 StringBuilder,这可以像您在问题中发布的代码一样以非常优化的方式完成。 p>

    • 索引charsstrings 每次向/从StringBuilder 添加和删除数据。请注意,索引意味着您需要分析您在StringBuilder 中添加或删除的每个string,这会为每个操作操作 带来一点开销。 p>

      • 您需要判断您的应用程序做的更多,哪些会干扰您的应用程序 - O(n) 搜索而不是 O(log(n)) O(n + m) 操作而不是 O(n) 操作。 (其中m 是每次插入/删除的开销除以平均插入/删除string 长度)

      • 基本索引说明:

      • 介于两者之间的索引也可以平衡(最大 2 chars index/最大 3 chars/etc...)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2013-05-07
      • 2016-06-30
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多