简体   繁体   中英

parse string value from a URL using c#

I have a string " http://site1/site2/site3 ". I would like to get the value of "site2" out of the string. What is the best algorythm in C# to get the value. (no regex because it needs to be fast). I also need to make sure it doesn't throw any errors (just returns null).

I am thinking something like this:

        currentURL = currentURL.ToLower().Replace("http://", "");

        int idx1 = currentURL.IndexOf("/");
        int idx2 = currentURL.IndexOf("/", idx1);

        string secondlevelSite = currentURL.Substring(idx1, idx2 - idx1);

Assuming currentURL is a string

string result = new Uri(currentURL).Segments[1]
result = result.Substring(0, result.Length - 1);

Substring is needed because Segments[1] returns "site2/" instead of "site2"

Your example should be fast enough. If we really want to be nitpicky, then don't do the initial replace, because that will be at least an O(n) operation. Do a

int idx1 = currentURL.IndexOf("/", 8 /* or something */);

instead.

Thus you have two O(n) index look-ups that you optimized in the best possible way, and two O(1) operations with maybe a memcopy in the .NET's Substring(...) implementation... you can't go much faster with managed code.

currentURL = currentURL.ToLower()。Replace(“ http://”,“”);

var arrayOfString = String.spilt(currentUrl.spit('/');

My assumption is you only need the second level. if there's no second level then it'll just return empty value.

    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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM