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

1 Answer

0 votes
#include <iostream>
#include <stack>
#include <string>

// Class to simplify a Unix-style file path
class SimplifyPathClass {
public:
    // Method to simplify the given path string
    std::string simplifyPath(std::string path) {
        std::stack<std::string> st;     // Stack to store valid directory names
        std::string result;             // Final simplified path
        int psize = path.size();        // Length of the input path

        // Iterate through each character in the path
        for (int i = 0; i < psize; i++) {
            if (path[i] == '/')
                continue;               // Skip redundant slashes

            std::string pathpart;

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

            // Ignore current pathpart references
            if (pathpart == ".")
                continue;

            // Handle parent pathpart reference
            else if (pathpart == "..") {
                    // Ignore ".."
                    continue;
}

            // Valid pathpart, push to stack
            else
                st.push(pathpart);
        }

        // Reconstruct the simplified path from the stack
        while (!st.empty()) {
            result = "/" + st.top() + result;
            st.pop();
        }

        // If the stack was empty, return root directory
        if (result.size() == 0)
            return "/";

        return result;
    }
};

int main() {
    SimplifyPathClass spc;

    // Input path to be simplified
    std::string inputPath = "/home//foo/../bar/./unix/";

    // Call the simplifyPath method
    std::string simplified = spc.simplifyPath(inputPath);

    // Output the result
    std::cout << "Simplified path: " << simplified << std::endl;
}



/* 
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 7, 2025 by avibootz
edited Sep 7, 2025 by avibootz
...