C# 使用c从URL解析字符串值#
我有一个字符串“”。我想从字符串中获取“site2”的值。C#中获得值的最佳算法是什么。(没有正则表达式,因为它需要快速)。我还需要确保它不会抛出任何错误(只返回null) 我是这样想的:C# 使用c从URL解析字符串值#,c#,C#,我有一个字符串“”。我想从字符串中获取“site2”的值。C#中获得值的最佳算法是什么。(没有正则表达式,因为它需要快速)。我还需要确保它不会抛出任何错误(只返回null) 我是这样想的: currentURL = currentURL.ToLower().Replace("http://", ""); int idx1 = currentURL.IndexOf("/"); int idx2 = currentURL.IndexOf("/", i
currentURL = currentURL.ToLower().Replace("http://", "");
int idx1 = currentURL.IndexOf("/");
int idx2 = currentURL.IndexOf("/", idx1);
string secondlevelSite = currentURL.Substring(idx1, idx2 - idx1);
你的例子应该足够快。如果我们真的想挑剔,那么就不要进行初始替换,因为这至少是一个O(n)操作。做一个
int idx1 = currentURL.IndexOf("/", 8 /* or something */);
相反
因此,您有两个以最佳方式优化的O(n)索引查找,还有两个O(1)操作,可能在.NET的
子字符串(…)
实现中有一个memcopy。。。使用托管代码的速度不可能更快。您的示例应该足够快。如果我们真的想挑剔,那么就不要进行初始替换,因为这至少是一个O(n)操作。做一个
int idx1 = currentURL.IndexOf("/", 8 /* or something */);
相反
因此,您有两个以最佳方式优化的O(n)索引查找,还有两个O(1)操作,可能在.NET的
子字符串(…)
实现中有一个memcopy。。。托管代码的运行速度再快不过了。currentURL=currentURL.ToLower()
currentURL=currentURL.ToLower().Replace(“http:/”,“”)
假设currentURL是一个字符串
string result = new Uri(currentURL).Segments[1]
result = result.Substring(0, result.Length - 1);
由于段[1]返回“site2/”而不是“site2”假设currentURL是字符串,因此需要使用子字符串
string result = new Uri(currentURL).Segments[1]
result = result.Substring(0, result.Length - 1);
之所以需要子字符串,是因为段[1]返回“site2/”而不是“site2”我的假设是您只需要第二级。如果没有第二级,那么它只返回空值
string secondLevel = string.Empty;
try
{
string currentURL = "http://stackoverflow.com/questionsdgsgfgsgsfgdsggsg/3358184/parse-string-value-from-a-url-using-c".Replace("http://", string.Empty);
int secondLevelStartIndex = currentURL.IndexOf("/", currentURL.IndexOf("/", 0)) + 1;
secondLevel = currentURL.Substring(secondLevelStartIndex, (currentURL.IndexOf("/", secondLevelStartIndex) - secondLevelStartIndex));
}
catch
{
secondLevel = string.Empty;
}
我的假设是你只需要第二层。如果没有第二级,那么它只返回空值
string secondLevel = string.Empty;
try
{
string currentURL = "http://stackoverflow.com/questionsdgsgfgsgsfgdsggsg/3358184/parse-string-value-from-a-url-using-c".Replace("http://", string.Empty);
int secondLevelStartIndex = currentURL.IndexOf("/", currentURL.IndexOf("/", 0)) + 1;
secondLevel = currentURL.Substring(secondLevelStartIndex, (currentURL.IndexOf("/", secondLevelStartIndex) - secondLevelStartIndex));
}
catch
{
secondLevel = string.Empty;
}
为什么要这么快?您正在分析多少个字符串?他们来自哪里?您确定这是代码中的瓶颈吗?为什么你不做任何正确的错误处理或处理https链接等?为什么它需要这么快?您正在分析多少个字符串?他们来自哪里?您确定这是代码中的瓶颈吗?为什么你没有做任何正确的错误处理或处理https链接等?回答得很好。我很高兴我不必做所有那些字符串索引,这更干净了。回答得好。我很高兴我不必做所有那些字符串索引,这更干净了。