如何剪切包含url的字符串并将其添加到数组中

时间:2014-03-25 10:18:13

标签: c# asp.net arrays string split

我正在构建一个自定义的痕迹,我想要每个LinkBut​​ton唯一的commandArgument url。

我有一个通用的字符串变量,它是一个url。每个子网站的名称可以不同,并且尽可能长时间不限hierchy。

String变量可能如下所示:

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

我想要做的是拆分字符串变量并将其添加到数组中,如下所示:

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

我尝试过以下代码:

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

但它并不像我希望它那样做。

适用任何形式的帮助

3 个答案:

答案 0 :(得分:9)

您可以使用扩展方法和一些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

答案 1 :(得分:0)

如果我理解你的问题,你想做类似下面的事情。请注意使用框架内置的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;
}

答案 2 :(得分:-4)

您可以使用自己的方法,但首先剪切网址字符串的第一部分:

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