ZOJ-1243(parse URL)

刷刷水題練練手速



#include <iostream>
#include <string>
using namespace std;

struct URL{
	string protocol;
	string host;
	string port;
	string path;
};
void parseUrl(const string& s, URL& url)
{
	size_t p = s.find("://");
	url.protocol = s.substr(0, p);
	size_t q = s.find_first_of(":/", p+3);
	if(q == string::npos){
		url.host = s.substr(p+3);
		url.port = url.path = "<default>";
		return;
	}
	else url.host = s.substr(p+3, q-p-3);

	size_t r = q;
	if(s[q] == ':'){
		r = s.find('/', q+1);
		if(r == string::npos) r = s.size();
		url.port = s.substr(q+1, r-q-1);
	}
	else url.port = "<default>";
	if(r < s.size()) url.path = s.substr(r+1);
	else url.path = "<default>";
}
inline void printUrl(const URL& url)
{
	cout << "Protocol = " << url.protocol << "\n";
	cout << "Host     = " << url.host << "\n";
	cout << "Port     = " << url.port << "\n";
	cout << "Path     = " << url.path << "\n";
}

int main()
{
	ios::sync_with_stdio(false);

	URL url;
	string s;
	int i = 1, n;
	for(cin >> n; i <= n; ++i){
		cin >> s;
		parseUrl(s, url);
		cout << "URL #" << i << "\n";
		printUrl(url);
		cout << "\n";
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章