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 ...
之间找到字符串答案 0 :(得分:1)
复制字符串的一部分(你的第一个SubString调用)只是为了继续搜索它对性能有害。相反,保留原始输入字符串,但使用带有起始索引的IndexOf上的重载,然后调整索引计算以相应地提取结果。
另外,知道这些字符串未本地化,您可能会在IndexOf中使用序数比较器获得一些。
的内容
public static string[] GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
{
string[] result = { "", "" };
int iIndexOfBegin = strSource.IndexOf(strBegin, StringComparison.Ordinal);
if (iIndexOfBegin != -1)
{
int iEnd = strSource.IndexOf(strEnd, iIndexOfBegin, StringComparison.Ordinal);
if (iEnd != -1)
{
result[0] = strSource.Substring(
iIndexOfBegin + (includeBegin ? 0 : strBegin.Length),
iEnd + (includeEnd ? strEnd.Length : 0) - iIndexOfBegin);
// advance beyond this segment
if (iEnd + strEnd.Length < strSource.Length)
result[1] = strSource.Substring(iEnd + strEnd.Length);
}
}
return result;
}
答案 1 :(得分:0)
对于您的示例输入,您似乎正在使用HTML片段。
我建议使用HTML Agility Pack来解析HTML - 它使用LINQ to XML或XPath类型语法以易于查询的方式公开结果。这是一个快速有效的图书馆。