如何将一个字符串转换为树型对象?

Triumph 2018-05-15 11:06:11
字符串如下:

一级
一一级
一二级
一二一级
一二二级
一三级
二级
三级
三一级
三二级
三三级
四级


转换为 List(Of TreeItem) 树型对象:

Class TreeItem
Property Name As String '树的名称
Property Items As List(Of TreeItem) '子节点列表
End Class
...全文
554 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
Triumph 2018-05-16
  • 打赏
  • 举报
回复
我自己解决了:

Public Class TreeItem
    ''' <summary>
    ''' 名称
    ''' </summary>
    Property Name As String

    ''' <summary>
    ''' 路径
    ''' </summary>
    Property Path As String

    ''' <summary>
    ''' 子节点
    ''' </summary>
    Property Items As New List(Of TreeItem)
End Class

Public Function ToTree(treeStr As String) As List(Of TreeItem)

    Dim treeList As New List(Of TreeItem)

    If String.IsNullOrWhiteSpace(treeStr) Then Return treeList

    '按行分隔字符串
    Dim treeArray() As String = treeStr.Split({vbCrLf}, StringSplitOptions.RemoveEmptyEntries)

    '创建一个栈
    Dim st As New Stack(Of TreeItem)
    Dim currentLevel As Integer = 0

    Items.Add(New TreeItem With {.Name = treeArray(0).Trim, .Path = .Name})
    st.Push(Items(0))
    For i As Integer = 1 To treeArray.Length - 1    '从索引 1 开始循环
        Dim _s As String = treeArray(i)
        Dim _count As Integer = Regex.Match(_s, "^((?:\s{" + indentCount.ToString + "})+)").Length '每 indentCount 个空白字符为一个层级,最后不足的忽略
        Dim _name As String = _s.Remove(0, _count).Trim
        If _name.IndexOf("/") > -1 Then Throw New Exception("【" + _name + "】无效。名称中不能包含字符"" / """)
        Dim _level As Integer = _count / indentCount    '缩进的层级
        If _level - currentLevel > 1 Then Throw New Exception(_name + " 的层级错误。")  '必须逐级递增。退级时可以跳过几层,代码在下面

        Dim _treeItem As New TreeItem With {.Name = _name}

        If _level > currentLevel Then
            _treeItem.Path = st.Peek.Path + "/" + _treeItem.Name
            st.Peek.Items.Add(_treeItem)
        Else
            For j As Integer = 0 To (currentLevel - _level) '退级
                st.Pop()
            Next
            If st.Count = 0 Then
                _treeItem.Path = _treeItem.Name
                Items.Add(_treeItem)
            Else
                _treeItem.Path = st.Peek.Path + "/" + _treeItem.Name
                st.Peek.Items.Add(_treeItem)
            End If
        End If
        st.Push(_treeItem)
        currentLevel = _level
    Next

    Return treeList

End Function

16,552

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧