BrokeMyLegBiking
BrokeMyLegBiking

Reputation: 5988

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

Upvotes: 0

Views: 982

Answers (4)

Carlos Muñoz
Carlos Muñoz

Reputation: 17804

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"

Upvotes: 2

Lester S
Lester S

Reputation: 730

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

Upvotes: 0

herzmeister
herzmeister

Reputation: 11287

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.

Upvotes: 1

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

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

Upvotes: 0

Related Questions