【发布时间】:2016-05-31 15:41:58
【问题描述】:
我正在编写一个C# 应用程序,该应用程序在string 调用的内容中追加、插入、替换和查找string 内容。多个名为 editObjects 的对象正在对同一个名为 string 的内容执行这些操作。
我目前正在将一个StringBuilder 对象传递给每个editObject 对象,然后每个editObject 对StringBuilder 对象执行操作。
这个问题有两个部分:
我是否正确地说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