[英]parse string value from a URL using c#
我有一个字符串“ http:// site1 / site2 / site3 ”。 我想从字符串中获取“ site2”的值。 C#中获得该值的最佳算法是什么? (没有正则表达式,因为它需要快速)。 我还需要确保它不会引发任何错误(只是返回null)。
我在想这样的事情:
currentURL = currentURL.ToLower().Replace("http://", "");
int idx1 = currentURL.IndexOf("/");
int idx2 = currentURL.IndexOf("/", idx1);
string secondlevelSite = currentURL.Substring(idx1, idx2 - idx1);
假设currentURL是一个字符串
string result = new Uri(currentURL).Segments[1]
result = result.Substring(0, result.Length - 1);
需要子字符串,因为Segments [1]返回“ site2 /”而不是“ site2”
您的示例应该足够快。 如果我们真的想挑剔,那就不要进行初始替换,因为这至少是一个O(n)操作。 做一个
int idx1 = currentURL.IndexOf("/", 8 /* or something */);
代替。
因此,您有两个以最佳方式优化的O(n)索引查找,以及两个.NET的Substring(...)
实现中可能带有内存复制的O(1)操作...您无法使用托管代码可以更快。
currentURL = currentURL.ToLower()。Replace(“ http://”,“”);
var arrayOfString = String.spilt(currentUrl.spit('/');
我的假设是您只需要第二级。 如果没有第二层,那么它将只返回空值。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.