How to simplify the directory path in C++
In this post, we will learn about how to simplify the directory path using the C++ programming language.
This post will help you to understand the process of simplifying the directory path using C++.
Simplify the directory path in C++
PROBLEM :
Suppose we are provided with a certain string (say S), representing an absolute path for a particular file or dictionary(in Unix format).
What we have to do is that we have to process this string in order to obtain a string that will be representing a simplified absolute path.
There are certain rules for the absolute simplified path :
Rule 1: It must begin with a backslash(“/”).
Rule 2:The absolute path must we not include any whitespaces.
INPUT: Provide string S as input.
OUTPUT: A String representing the simplified directory path is produced as output.
Let us consider some examples to better understand the process:
Ex1:Suppose Input String S =”/Rocky/”
Then the DesiredĀ Output will be = “/Rocky”
Ex2:Suppose Input String S =”/Donaldduck/”
Then the DesiredĀ Output will be = “/Donaldduck”
CODE:
#include <bits/stdc++.h> using namespace std; string solution(string S) { string r; string d; stack<string> s; r.append("/"); int l = S.length(); //len to l for (int i = 0; i < l; i++) { d.clear(); while (S[i] == '/') i++; while (i < l && S[i] != '/') { d.push_back(S[i]); i++; } if (d.compare("..") == 0) { if (!s.empty()) s.pop(); } else if (d.compare(".") == 0) continue; else if (d.length() != 0) s.push(d); } stack<string> str; // st1 to str while (!s.empty()) { str.push(s.top()); s.pop(); } while (!str.empty()) { string temp = str.top(); if (str.size() != 1) r.append(temp + "/"); else r.append(temp); str.pop(); } return r; } int main() { string str("/Donaldduck/"); string r = solution(str); cout <<r; return 0; }
OUTPUT:
/Donaldduck
Leave a Reply