日期:2014-05-18 浏览次数:20783 次
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var rs = new RecursiveString("[黑龙江[哈尔滨[南岗;道里]]", null); Console.WriteLine(rs.Name); } } class RecursiveString { private string _data = ""; public RecursiveString(string value, RecursiveString parent) { _data = value; Parent = parent; } public string Name { get { return Regex.Match(_data, @"^\[(.+?)\[|;|\]").Groups[1].Value; } } public RecursiveString Parent { get; private set; } public List<RecursiveString> Items { get { return null; } } } }
------解决方案--------------------
【省A【市AA【区AAA;区AAB】】;【市AB【区ABA;区ABB】】】;【省B【市BA【区BAA;区BAB】】】;【省C【市CA【区CAA】】】;【省D【市DA】】
private void ShowData(string str) { this.treeView1.Nodes[0].Nodes.Clear(); //始终为当前节点的引用 TreeNode node = this.treeView1.Nodes[0]; StringBuilder sbContent = new StringBuilder(); for (int i = 0; i < str.Length; i++) { char tmp = str[i]; if (tmp.Equals('【')) { if (sbContent.Length != 0) { node.Text = sbContent.ToString(); sbContent.Clear(); } TreeNode node2 = new TreeNode(); node.Nodes.Add(node2); node = node2; } else if (tmp.Equals('】')) { if (sbContent.Length > 0) { node.Text = sbContent.ToString(); sbContent.Clear(); } node = node.Parent; } else if (tmp.Equals(';')) {//数据结束 if (sbContent.Length > 0) { node.Text = sbContent.ToString(); sbContent.Clear(); } if (str[i + 1] < str.Length && !str[i + 1].Equals('【')) { TreeNode node2 = new TreeNode(); node.Parent.Nodes.Add(node2); node = node2; } } else {//数据 sbContent.Append(tmp); } } this.treeView1.ExpandAll(); }
------解决方案--------------------
var temp = string.ToCharArray()
扫描temp,碰到[的时候入栈,同时建立新的节点,碰到]的时候出栈,将出栈数据放到刚刚新建的节点的子节点集合中,直到再碰到[继续入栈
大致就是这样