ccf 201604-3 路径解析

ccf 201604-3 路径解析

 string.find()

返回字符串s1在s中第一次出现的位置,如果没有找到,则返回-1

string.erase()

erase函数的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)

 1 #include<iostream>
 2 #include<cstring>
 3 #include<vector>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     vector<string> ans;
 9     int n;
10     string now;
11     cin>>n>>now;
12     getchar();
13     for(int i=0;i<n;i++)
14     {
15         string loc;
16         getline(cin,loc);//读入一行
17 
18         if(loc[0] != '/'){//相对路径
19             loc = now +"/"+loc;
20         }
21         if(loc.size()==0)
22         {//若路径为空字符串,则正规化操作的结果是当前目录。
23             loc = now;
24         }
25         int pos;
26         ///1.需要去除“///
27         while((pos = loc.find("//")) !=-1)
28         {
29             int Count = 2;
30             while(loc[pos+Count] == '/') Count ++;
31             loc.erase(pos,Count-1);
32         }
33         ///2.需要去除“/../”
34         while((pos = loc.find("/../")) != -1)
35         {
36             int Count = 3;
37             if(pos != 0)
38             {
39                 Count = 4;
40                 while(pos-1>=0 && loc[pos-1] != '/'){
41                     pos--;Count++;
42                 }//去除该层目录,到达上一层目录
43             }
44             loc.erase(pos,Count);
45         }
46         ///3.需要去除“/./”
47         while((pos = loc.find("/./")) != -1)
48         {
49             loc.erase(pos,2);
50         }
51         ///4.需要去除最后一个"/"
52         if(loc.size()>1 && loc[loc.size()-1] == '/'){
53             loc[loc.size()-1] = '';
54         }
55 
56         ans.push_back(loc);
57     }
58     for(int i=0;i<ans.size();i++)
59     {
60         cout<<ans[i]<<endl;
61     }
62     return 0;
63 }

原文地址:https://www.cnblogs.com/yxh-amysear/p/8537553.html