c#轮廓编号

时间:2011-09-30 15:35:43

标签: c#

我正在尝试在C#中开发一个算法,该算法可以获取URL的数组列表并将其输出到大纲编号列表中。

你可以想象我需要一些帮助。有没有人对用于生成此列表的逻辑有任何建议?

示例输出:

1   - http://www.example.com/aboutus
1.2 - http://www.example.com/aboutus/page1
1.3 - http://www.example.com/aboutus/page2
1.3.1   - http://www.example.com/aboutus/page2/page3
1.3.1.1 - http://www.example.com/aboutus/page2/page3/page4
1.3.2   - http://www.example.com/aboutus/page5/page6
1.3.2.1 - http://www.example.com/aboutus/page5/page7/page9
1.3.2.2 - http://www.example.com/aboutus/page5/page8/page10

1.4 - http://www.example.com/aboutus/page10
1.4.1   - http://www.example.com/aboutus/page10/page11
1.4.2   - http://www.example.com/aboutus/page10/page12

1.1.5   - http://www.example.com/aboutus/page13

1.1.6   - http://www.example.com/aboutus/page14
1.1.6.1 - http://www.example.com/aboutus/page14/page15
1.1.6.2 - http://www.example.com/aboutus/page14/page16
1.1.6.3 - http://www.example.com/aboutus/page14/page17

......等等

4 个答案:

答案 0 :(得分:8)

看一下System.URI类。它应该有一些应该有用的方法和特性,比如将uri分成其分段部分的segment属性(通过斜线划分)。您可以创建段数组的列表,对列表进行排序,然后简单地迭代列表调整数字,具体取决于当前列表索引段是否与先前的列表索引段匹配。

答案 1 :(得分:3)

您可能必须删除协议和查询字符串参数,因此建议+1使用System.URI类来处理它。

至于以树形打印它 - 直接的方法是使用Dictionary<string, string>来保持子(键)与父(值)的关联。

另一种方法是利用List<T>.Sort,例如像这样:

public static void Print(List<string> list)
{
    var path = new Stack<string>();
    var count = new Stack<int>();
    path.Push("");
    count.Push(0);

    list.Sort(new Comparison<string>(UrlComparison));

    foreach (var x in list)
    {
        while (!x.StartsWith(path.Peek())) { path.Pop(); count.Pop(); }
        count.Push(count.Pop() + 1);
        foreach(var n in count.Reverse()) Console.Write("{0}.", n);
        Console.WriteLine(" {0}", x);
        path.Push(x);
        count.Push(0);
    }
}

不幸的是,p.campbell是正确的,这里实际上需要进行自定义比较,这使得此实现仍然非常高效,但更笨重(?:-abuse警告):

public static int UrlComparison(string x, string y)
{
    if (x == null && y == null) return 0;
    if (x == null) return -1;
    if (y == null) return 1;
    for(int n = 0; n < Math.Min(x.Length, y.Length); n++)
    {
        char cx = x[n], cy = y[n];
        if(cx == cy) continue;
        return
            (cx == '/' || cx == '.' || cx == '?') ? -1 :
            (cy == '/' || cy == '.' || cy == '?') ? 1 :
            (cx > cy) ? 1 : -1;
    }
    return (x.Length == y.Length) ? 0 : (x.Length > y.Length) ? 1 : -1;
}
PS:只是放一个免责声明,我觉得堆栈逻辑是合理的,但要理解起来有点复杂。在一个长期项目中,我会坚持使用子母词典。

答案 2 :(得分:2)

这可能是Generic Tree Collection会有所帮助。

Code Project上的树集合很少:onetwo

答案 3 :(得分:0)

我认为您需要实现某种树集合来处理订单。因为如果您添加了名为http://www.example.com的新链接,那么该链接将变为1而不是http://www.example.com/aboutus

然后你可以打印树的有序遍历,这将非常简单。

相关问题