我正在尝试在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
… 等等
解决方法
您可能必须删除协议和查询字符串参数,因此建议使用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是对的,这里实际上需要自定义比较,这使得这个实现仍然非常高效,但更笨重(?: – 滥用警告):
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:只是放一个免责声明,我觉得堆栈逻辑是合理的,但要理解起来有点复杂.在长期项目中,我会坚持使用子母字典.