首页 > 试题广场 >

编写程序实现给定一个 linux 风格的绝对路径,要求 .

[问答题]

编写程序实现给定一个 linux 风格的绝对路径,要求 . // 时忽略, .. 返回上一层的路径,

比如: path=”/a/./b//../c”/a/c”

使用语言不限

#include <iostream>
#include <string>
#include <stack>

using namespace std;

int main() {
    stack<string> st;
    string path;
    
    while(cin >> path) {
        int len = path.size();
        string temp = "";
        for(int i = 0;i < len;++i) {
            if('/' == path[i]) {
                if(".." == temp) {
                    st.pop();
                }
                else if("." != temp && "" != temp) {
                    st.push(temp);
                }
                temp = "";
            }
            else {
                temp += path[i];
                if((len - 1) == i) {
                    st.push(temp);
                }
            }
        }
        stack<string> st2;
        while(!st.empty()) {
            st2.push(st.top());
            st.pop();
        }
        string dest = "";
        while(!st2.empty()) {
            dest += "/";
            dest += st2.top();
            st2.pop();
        }
        cout << dest << endl;
    }
    
    return 0;
}
发表于 2017-03-02 00:57:24 回复(0)