How can I cut a string containing a url and add it to an array

I am creating a custom palette and I want each unique LinkButtonArgument URL.

I have a shared string variable which is a url. The name of each website can be different and as long as possible, the character is not limited.

String variable might look like this:

http://site/org/content/Change/Book/process/item

what I would like to do is split the string variable and add it to the array so that it looks like this:

http://site/org
http://site/org/content/
http://site/org/content/Change/
http://site/org/content/Change/Book/
http://site/org/content/Change/Book/process/
http://site/org/content/Change/Book/process/item

I tried the following code:

 private void AddBreadCrumb(SPWeb web)
    {
     var webUrl = web.Url;
     var linkList = new List<string>(webUrl.Split('/'));
     // etc..
    }

But he does not do as I want it.

Any kind of help appiacted

+4
source share
3 answers

LINQ:

public static IEnumerable<string> ParseUrl(this string source)
{
    if(!Uri.IsWellFormedUriString(source, UriKind.Absolute)) 
         throw new ArgumentException("The URI Format is invalid");

    var index = source.IndexOf("//");
    var indices = source.Select((x, idx) => new {x, idx})
                .Where(p => p.x == '/' && p.idx > index + 1)
                .Select(p => p.idx);

    // Skip the first index because we don't want http://site
    foreach (var idx in indices.Skip(1))
    {
       yield return source.Substring(0,idx);
    }
    yield return source;
}

:

string url = "http://site/org/content/Change/Book/process/item";
var parts = url.ParseUrl();

LINQPad:

enter image description here

+9

, - . Uri, .

, .

var breadCrumbs = 
    EnumerateBreadCrumbs(@"http://site/org/content/Change/Book/process/item")
    .Select(uri => uri.ToString())
    .ToArray();


private IEnumerable<Uri> EnumerateBreadCrumbs(string url)
{
    var raw = new Uri(url);

    var buffer = new UriBuilder(raw.Scheme, raw.Host, raw.Port);
    yield return buffer.Uri;

    for (var i = 1; i < raw.Segements.Length; i++)
    {
        if (raw.Segments[i] == "/")
        {
            continue;
        }

        buffer.Path += raw.Segments[i];
        yield return buffer.Uri;
    }

    if (raw.Query.Length > 1)
    {
        buffer.Query = new string(raw.Query.Skip(1).ToArray());
        yield return buffer.Uri;
    }

    if (raw.Fragment.Length < 2)
    {
        yield break;
    }

    buffer.Fragment = new string(raw.Fragment.Skip(1).ToArray());
    yield return buffer.Uri;
}
0

You can use your own method, but first cut off the first part of the URL string:

var webUrl=web.Url;
webUrl=webUrl.SubString(7);//removing "http://"
var linkList=new List<string>(webUrl.Split('/'));
-4
source

Source: https://habr.com/ru/post/1533307/


All Articles