Combine overlapping urls in C#
I've got two Urls. A server and a relative url that I would like to combin开发者_运维技巧e. 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";
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.
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.
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;
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());
精彩评论