Untitled
unknown
c_cpp
a year ago
1.3 kB
2
Indexable
Never
#include <iostream> #include <sstream> #include <vector> #include <algorithm> using namespace std; vector<string> tokenize(const string& str, char delimiter) { stringstream ss(str); string token; vector<string> tokens; while (getline(ss, token, delimiter)) { if (!token.empty()) { tokens.push_back(token); } } return tokens; } string relative_path(const string& s1, const string& s2) { vector<string> tokens1 = tokenize(s1, '/'); vector<string> tokens2 = tokenize(s2, '/'); int common_length = 0; while (common_length < min(tokens1.size(), tokens2.size()) && tokens1[common_length] == tokens2[common_length]) { common_length++; } string result = "cd "; for (int i = common_length; i < tokens1.size(); ++i) { result += "../"; } for (int i = common_length; i < tokens2.size(); ++i) { result += tokens2[i]; if (i < tokens2.size() - 1) { result += "/"; } } return result; } int main() { string s1 = "/home/ubuntu/finplus/cards/order"; string s2 = "/home/ubuntu/finplus/expenses/records"; string rel_path = relative_path(s1, s2); cout << rel_path << endl; return 0; }