首页 百科知识 路径解析(解法二)

路径解析(解法二)

时间:2022-09-22 百科知识 版权反馈
【摘要】:本程序用第2中方法来实现。因为C++的cin输入字符串时,无法输入空串,而C的库函数中已经不建议使用函数gets(),所以自己编写一个读入一行的函数mygetline(),该函数可以输入空行。


这是一个输入字符串处理的问题,可以有各种各样的处理方法。

1.直接用C语言及其库函数来处理。这是最基本的最高效的(时间上)的方法,逻辑相对会复杂一些。

2.用C++的string类有关的方法(函数)来处理。这种方法编程效率比较高。

3.采用混合方法来处理。既使用C语言的库函数,也使用C++的类库。

这个问题有一个陷阱,就是输入的字符串可能是空串。

本程序用第2中方法来实现。因为C++的cin输入字符串时,无法输入空串,而C的库函数中已经不建议使用函数gets(),所以自己编写一个读入一行的函数mygetline(),该函数可以输入空行。使用C++类string的各种方法(函数)也同样可以实现字符串的处理。


/* CCF201604-3 路径解析 */  

  

#include <iostream>  

#include <string>  

  

using namespace std;  

  

const int N = 1000;  

char s[N+1];  

  

void mygetline(char *pc)  

{  

    char c;  

  

    while((c=getchar()) != '\n' && c !=EOF)  

        *pc++ = c;  

    *pc = '\0';  

}  

  

int main()  

{  

    int p, pos;  

    string cp, line;  

  

    // 输入数据:整数p和当前目录  

    cin >> p >> cp;  

    getchar();  

  

    // 输入p个路径进行正规化处理  

    for(int i=1; i<=p; i++) {  

        // 输入路径  

        mygetline(s);  

        line = s;  

  

        // 非根路径处理  

        if(line[0] != '/')  

            line = cp + "/" + line + "/";  

  

        // 去除多个"/"  

        while((pos = line.find("//")) != -1) {  

            int count = 2;  

            while(line[pos + count] == '/')  

                count++;  

            line.erase(pos, count-1);  

        }  

  

        // 去除"./"  

        while((pos = line.find("/./")) != -1)  

            line.erase(pos + 1, 2);  

  

        // 去除最后的"/"  

        if(line.size() > 1 && line[line.size() - 1] == '/')  

            line.erase(line.size() - 1);  

  

        // 去除"../"  

        while((pos = line.find("/../")) != -1) {  

              if(pos == 0)  

                  line.erase(pos, 3);  

              else {  

                  int spos;  

                  spos = line.rfind("/", pos - 1);  

                  line.erase(spos, pos - spos + 3);  

              }  

  

              if(line.size() == 0)  

                  line = "/";  

        }  

  

        // 输出结果  

        cout << line << endl;  

    }  

  

    return 0;  

}  

免责声明:以上内容源自网络,版权归原作者所有,如有侵犯您的原创版权请告知,我们将尽快删除相关内容。

我要反馈