路径解析

本文介绍了一种处理文件路径规范化的方法,包括对绝对路径和相对路径的处理,通过使用字符串流和栈来解析路径并移除多余的'.'和'..'部分,确保路径的正确性和简洁性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//刚开始写只有90分  后来看了别人的题解后发现有一种情况是所给当前路径为空..........然后...需要在给相对路径加入时多个.size == 0 和.size!=0 的条件....不然不会有结果.    然后感觉为绝对路径时...也应该加个条件吧 我没加...

#include<iostream>
#include<cstdio>
#include<sstream>
#include<cmath>
#include<vector>

using namespace std;

vector<string> st1, st2;
void InStack(string s) {
	string flag="/";
	int position=0;
	while((position=s.find(flag,position))!=string::npos) {
		s.replace(position, 1, " ");
		position++;
	}
//	cout << s << endl;
	stringstream ss(s);

	while(ss >> s) {
		if(s == "..") {
			if(st2.size())

				st2.pop_back();
		} else if(s == ".") {
			;
		} else st2.push_back(s);
	}
	
	if(st2.size() == 0){
		
	}

}

void InStack1(string s) {
	string flag="/";
	int position=0;
	while((position=s.find(flag,position))!=string::npos) {
		s.replace(position, 1, " ");
		position++;
	}
//	cout << s << endl;
	stringstream ss(s);

	while(ss >> s) {
		if(s == "..") {
			if(st1.size())
				st1.pop_back();
		} else if(s == ".") {
			;
		} else st1.push_back(s);
	}
	for(int i=0; i<st1.size(); i++) {
		cout << "/" << st1[i];
	}
	if(st1.size() == 0) {
		cout << "/";
	}
	cout << endl;

}

void InStack2(string s) {
	string flag="/";
	int position=0;
	while((position=s.find(flag,position))!=string::npos) {
		s.replace(position, 1, " ");
		position++;
	}

	stringstream ss(s);
	while(ss >> s) {
		if(s == "..") {
			if(st2.size())
				st2.pop_back();
		} else if(s == ".") {
			continue;
		} else {
			if(st2.size() && st2.back() == s)//...有种情况是st2.size == 0... 
				continue;
			st2.push_back(s);
		}
	}
	for(int i=0; i<st2.size(); i++) {
		cout << "/" << st2[i];
	}
	if(st2.size() == 0) {
		cout << "/";
	}
	cout << endl;
}

int main() {
	int n;
	string cur, s;

	cin >> n;
	cin.get();
	getline(cin, cur);//绝对路径


	for(int i=0; i<n; i++) {

		while(!st1.empty()) {
			st1.pop_back();
		}
		while(!st2.empty()) {
			st2.pop_back();
		}
		getline(cin, s);

		if(s[0] == '/')//绝对路径
			InStack1(s);
		else {//相对路径
			InStack(cur);
			InStack2(s);
		}
	}

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值