3

I've got two Urls. A server and a relative url that I would like to combine. The problem is that part of the url's may well overlap. I've done this using some horrible string manipulation but would like to put this out there and see if there is a nice and clean way of doing it.

string siteUrl = "http://seed-dev6/sites/irs"; string formUrl = "/sites/irs/Forms/testform.xsn"; 

4 Answers 4

3

I would split the URLs based on their path separator /, merge the lists without duplicates while preserving order, and then concatenate them into a single URL string.

This avoids the crazy string manipulation and search you need to do. THe only complicating factor is making the code capable of dealing with different case (upper vs. lower), and web escape code %20, etc.

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

1 Comment

I've gone for your approach, it's not perfect but it's good enough for what I need and is a lot quicker to implement.
2

This writeup of the Knuth-Morris-Pratt algorithm discusses an algorithm for finding the overlap of two words. In fact, they even provide an algorithm:

overlap[0] = -1; for (int i = 0; pattern[i] != '\0'; i++) { overlap[i + 1] = overlap[i] + 1; while (overlap[i + 1] > 0 && pattern[i] != pattern[overlap[i + 1] - 1]) overlap[i + 1] = overlap[overlap[i + 1] - 1] + 1; } return overlap; 

You would have to write your own for C#, but this (along with the article) would be a good start.

Comments

1

This should do the trick. Might also use Path.DirectorySeparatorChar instead of '/'.

char delim = '/'; string siteUrl = "http://seed-dev6/sites/irs"; string formUrl = "/sites/irs/Forms/testform.xsn"; string fullUrl = string.Join( new string(delim,1), siteUrl.Split(delim).Concat(formUrl.Split(delim)).Distinct().ToArray()); 

Comments

0
 string siteUrl = "http://seed-dev6/sites/irs"; string formUrl = "/sites/irs/Forms/testform.xsn"; string result = siteUrl + formUrl; for (int n = 1; n < formUrl.Length; ++n) { if (siteUrl.EndsWith(formUrl.Substring(0, n))) result = siteUrl + formUrl.Substring(n); } return result; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.