[C ++] - simplified explanations of the cattle off the Unix-style path

Title Description

Here Insert Picture Description
(Just saw this question, my mind is Mongolian, and do not let us know he doing, but later found that with a little Linux or relationship) The following is the idea (although very long, but the cow's solution is easy to understand ):

1, / indicates the root directory, linux / uinx directory structure is a tree, i.e. the root of the root of the tree, it is impossible to continue the upward.
2 ,. represents the current directory.
3, ... indicate the parent directory.
4, / is also used for the partition between directories, such as / a / b b represents the path a path under the root directory; a / b b represents a path of the current directory path.
5, / delimiter when used, the number may be more or less, and as // a ///// b / a / b is the same. Note // a ///// b and a / b is not the same, because the former has a root directory. End / meaningless, such as a / b and a / b / is the same.

We can push the stack to simulate exit into the directory catalog, but the stack stl not apply because only stack sequentially output from the top of the stack, processing notes trouble, so use vector. A temporary variable ret, for saving character between two /.
1, if ret == "." Do nothing
2, if ret == "..." pop
3, otherwise, ret stack.

Caveats:
1. To determine the stack before the stack is not empty, because in linux, unix, command cd / ... / ... / is legal, the result is into the root directory, is not possible in the upward.
2, before the stack is to be determined whether an empty string str, // Similar to exclude because this case is a ///// b.
3, the final result, if the stack is empty, but also output a /

Code:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <stack>
#include <vector>
#include <math.h>
using namespace std;

//简化Uinx风格的路径
int main()
{
	string str;
	while (cin>>str)
	{
		int i = 0;
		int j = 0;
		string ret;
		vector<string> s;
		vector<string> ::iterator it;
		for (i = 0; i < str.size(); i++)
		{
			if (str[i] == '/')
			{
				j = i + 1;
				while (j<str.size()&&str[j] != '/')
				{
					j++;
				}
				if (i + 1 < str.size())
				{
					ret = str.substr(i + 1, j - i - 1);
					if (ret == "..") //出栈前判断是否为空
					{
						if (!s.empty())
						{
							s.pop_back();
						}
					}
					else if (ret == ".")
					{
						; //什么也不做
					}
					else if (!ret.empty())  //入栈之前看其截取的是否为空
					{
						s.push_back(ret);
					}
				}
				
			}
			i = j - 1;
		}
		if (s.empty())  //如果是空的就输出"/"
		{
			cout << "/" << endl;
		}
		else
		{
			for (it = s.begin(); it != s.end(); ++it)
			{
				cout << "/" << *it << endl;
			}
		}
	}
	system("pause");
	return 0;
}

Screenshot result:
Here Insert Picture Description
I think this question is very interesting, first recorded

Published 42 original articles · won praise 13 · views 1765

Guess you like

Origin blog.csdn.net/Vicky_Cr/article/details/105270491