2011-03-23 53 views
1

这可能是很简单,但想知道之间的检索字符串,没有任何替代品找到一个源字符串,通过它传递开始和结束串从源字符串,它是2串

之间的串以下代码是可以实现的,但是这里有比这更好的代码,因为我认为如果在很多条件下使用,这会使系统变慢。

string strSource = "The LoadUserProfile call failed with the following error: "; 
    string strResult = string.Empty; 
    string strStart = "loaduserProfile"; 
    string strEnd = "error"; 

    int startindex = strSource.IndexOf(strStart, StringComparison.OrdinalIgnoreCase); 
    int endindex = strSource.LastIndexOf(strEnd, StringComparison.OrdinalIgnoreCase); 

    startindex = startindex + strStart.Length; 

    int endindex = endindex - startindex; 
    strResult = strSource.Substring(startindex, endindex); 

感谢 D.Mahesh

回答

0

你的代码是美丽的地方,对字符串操作。我不认为它可以在算法上变得更快。你也可以使用正则表达式来做到这一点,但我不认为在这种情况下结果会更快。

如果您不需要区分大小写,将StringComparison.OrdinalIgnoreCase更改为StringComparison.Ordinal应该提供一些加速。

否则,您可能不得不在其他地方寻找速度改进。

+0

一个正则表达式的方法可能会产生的C#代码更少,但。 OP应该调查是否可以直接从不同的和结构化的源获得所需的字符串(信息)。 – 2011-03-23 11:33:59

+1

使用正则表达式的代码行数可能会更少,但速度不会更快,并且它是否会更容易理解是值得怀疑的。 – Gabe 2011-03-23 12:12:26

1

使用正则表达式并找到组值,但不确定是否会更快或更慢。

下面是一个例子代码来实现这个使用正则表达式(无VS,所以借口如果有语法错误)

string pattern = Regex.Escape(strStart) + "(?<middle>[\s\S]*)" + Regex.Escape(strEnd); 
Match match = Regex.Match(strSource, pattern); 
if (match.Success) 
{ 
    // read the group value matches the name "middle" 
    ...... 
}