【发布时间】:2012-01-26 18:07:45
【问题描述】:
public static string[] GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
{
string[] result = { "", "" };
int iIndexOfBegin = strSource.IndexOf(strBegin);
if (iIndexOfBegin != -1)
{
// include the Begin string if desired
if (includeBegin)
iIndexOfBegin -= strBegin.Length;
strSource = strSource.Substring(iIndexOfBegin + strBegin.Length);
int iEnd = strSource.IndexOf(strEnd);
if (iEnd != -1)
{
// include the End string if desired
if (includeEnd)
iEnd += strEnd.Length;
result[0] = strSource.Substring(0, iEnd);
// advance beyond this segment
if (iEnd + strEnd.Length < strSource.Length)
result[1] = strSource.Substring(iEnd + strEnd.Length);
}
}
return result;
}
用法:
string[] result = null;
result = HtmlHelper.GetStringInBetween(bits[0], bits[1], tagValuePair.Value, true, true);
我正在使用 dottrace,这种方法占用了我 33% 的 CPU。我该如何优化它。因为它我的应用程序崩溃或者我的内存不足。这种方法是静态的,聪明吗?
dottrace 显示 30% 的 cpu 使用率:
System.String.IndexOf(String, Int32, Int32, StringComparison)
编辑:
GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
strBegin = "<td class=\"m92_t_col2\">"
strEnd = "</td>"
strSource = "xxxxxxxx<td class=\"m92_t_col2\">Di. 31.01.12</td>xxxxxxxxxxxxxx
includeBegin = true
includeEnd = true
then i will get result
result[0] = "<td class=\"m92_t_col2\">Di. 31.01.12</td>"
希望这有助于此方法的作用。尝试在 strBegin 和 strEnd 之间查找字符串...
【问题讨论】:
-
您是否考虑过为此使用正则表达式?
-
@Oded 我做到了,但我对正则表达式非常糟糕,所以我用 indexof 编写代码,我现在认为这是个坏主意......
-
dottrace 是否告诉您对
System.String.IndexOf(String, Int32, Int32, StringComparison)的调用来自GetStringInBetween如果是,您可以简单地减少对GetStringInBetween的调用 -
是的,它来自 GetStringInBetween。我怎样才能减少代码?我不太了解正则表达式
-
正则表达式与它们操作的文本密切相关 - 如果不了解更多关于输入类型的信息,就不可能提出建议。
标签: c# performance-testing dottrace