0

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);
1
  • 2
    Why does it need to be so fast? How many strings are you parsing? Where do they come from? Are you sure this is the bottleneck in your code? Why aren't you doing any proper error handling or handling https links, etc? Commented Jul 28, 2010 at 23:00

4 Answers 4

2

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"

Sign up to request clarification or add additional context in comments.

1 Comment

nice answer. I am glad that I don't have to do all those string indexes, this is much cleaner.
1

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.

Comments

0

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.