在VB.NET中将分隔变量分隔为数组元素

时间:2012-03-05 04:18:56

标签: vb.net arrays variables delimiter

我在vb.net中的长变量包含以下信息,

Dim g As String = "$C:\Program Files\Cavaj Java Decompiler\cavaj.exe$C:\Users\Yoosuf\AppData\Local\Google\Chrome\Application\chrome.exe$C:\Program Files\DVD Maker\dvdmaker.exe$C:\Program Files\Adobe\Adobe Photoshop CS2\ImageReady.exe$C:\Program Files\Java\jre6\bin\javaws.exe$"

$符号用作分隔符,用于将每个项目与另一个项目分开。我需要在列表框的每个路径的末尾添加exe文件名。但是,将变量检索到单个数组元素的初始过程无法正常工作。

Dim strArr() As String = g.Split("$")  'This variable is empty
For count = 0 To strArr.Length - 1
Dim arr As String = strArr(count).Split("\")

Dim strval As String = ""
For i As Integer = 3 To arr.Length - 1
        strval = arr(i)
        Dim j As Integer = arr.Length - 1
        strval = arr(j)
        Dim result As String = strval.Substring(g.Length - 5)
        result = g.Substring(g.LastIndexOf("\") + 1)
        ListBox1.Items.Add(result)
 Next
Next

2 个答案:

答案 0 :(得分:4)

无需完成所有这些工作。 System.IO.Path 类有为您执行此操作的方法。您想使用 System.IO.Path.GetFileName System.IO.Path.GetFileNameWithoutExtension 。由于您已经拆分了所有文件路径,只需将这些路径传递给上述任一方法,然后将结果添加到列表框中。

Dim strArr() As String = g.Split("$")
For Each path As String In strArr
    ListBox1.Items.Add(System.IO.Path.GetFileName(path))
Next

答案 1 :(得分:1)

请参阅以下代码和相关评论。另外,我根据你想要做的事情评论了一些我觉得不需要的代码。

Dim strArr() As String = g.Split("$")  'This variable is empty
        For count = 0 To strArr.Length - 1
            Dim arr() As String = strArr(count).Split("\") ' Split returns an array

            Dim strval As String = ""
            For i As Integer = 3 To arr.Length - 1
                'strval = arr(i)
                Dim j As Integer = arr.Length - 1
                strval = arr(j)
                'Dim result As String = strval.Substring(g.Length - 5)
                'result = g.Substring(g.LastIndexOf("\") + 1)
                ListBox1.Items.Add(strval)
            Next
        Next