[英]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.