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

1 Answer

0 votes
object SimplifyPathApp {

  // Function to simplify a Unix-style file path
  def simplifyPath(path: String): String = {
    val stack = scala.collection.mutable.Stack[String]() // Stack to store valid directory names
    var result = ""                                      // Final simplified path
    val psize = path.length                              // Length of the input path
    var i = 0

    // Iterate through each character in the path
    while (i < psize) {
      if (path(i) == '/') {
        i += 1 // Skip redundant slashes
      } else {
        val pathpart = new StringBuilder

        // Extract the next pathpart until the next slash
        while (i < psize && path(i) != '/') {
          pathpart += path(i)
          i += 1
        }

        val part = pathpart.toString

        // Ignore current pathpart references
        // Handle parent pathpart reference (ignored instead of popping)
        // Valid pathpart, push to stack
        if (part.nonEmpty && part != "." && part != "..") {
          stack.push(part)
        }
      }
    }

    // Reconstruct the simplified path from the stack
    while (stack.nonEmpty) {
      result = "/" + stack.pop() + result
    }

    // If the stack was empty, return root directory
    if (result.isEmpty) "/" else result
  }

  def main(args: Array[String]): Unit = {
    // Input path to be simplified
    val inputPath = "/home//foo/../bar/./unix/"

    // Call the simplifyPath function
    val simplified = simplifyPath(inputPath)

    // Output the result
    println(s"Simplified path: $simplified")
  }
}



/*
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 9, 2025 by avibootz
...