How to simplify path (remove ".." and "." and replace multiple “////” with one single “/”) in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

' Class to simplify a Unix-style file path
Public Class SimplifyPathClass
    ' Method to simplify the given path string
    Public Function SimplifyPath(ByVal path As String) As String
        Dim st As New Stack(Of String)()   ' Stack to store valid directory names
        Dim result As String = ""          ' Final simplified path
        Dim psize As Integer = path.Length ' Length of the input path

        ' Iterate through each character in the path
        Dim i As Integer = 0
        While i < psize
            If path(i) = "/"c Then
                i += 1
                Continue While             ' Skip redundant slashes
            End If

            Dim pathpart As String = ""

            ' Extract the next pathpart until the next slash
            While i < psize AndAlso path(i) <> "/"c
                pathpart &= path(i)
                i += 1
            End While

            ' Ignore current pathpart references
            If pathpart = "." Then
                Continue While
            End If

            ' Handle parent pathpart reference
            If pathpart = ".." Then
                ' Ignore ".." instead of popping
                Continue While
            End If

            ' Valid pathpart, push to stack
            st.Push(pathpart)
        End While

        ' Reconstruct the simplified path from the stack
        While st.Count > 0
            result = "/" & st.Pop() & result
        End While

        ' If the stack was empty, return root directory
        If result.Length = 0 Then
            Return "/"
        End If

        Return result
    End Function

End Class

Module Program
    Sub Main()
        Dim spc As New SimplifyPathClass()

        ' Input path to be simplified
        Dim inputPath As String = "/home//foo/../bar/./unix/"

        ' Call the SimplifyPath method
        Dim simplified As String = spc.SimplifyPath(inputPath)

        ' Output the result
        Console.WriteLine("Simplified path: " & simplified)
    End Sub
End Module

			

'run:
'
' Simplified path: /home/foo/bar/unix
'


 



answered Sep 7 by avibootz
...