我需要将URL分割成主机、端口和资源。我查阅了很多参考资料,但没有找到可以帮助我的内容。这就是我想要的格式:
例如: URL为-1.2.3.4:5678/path1/path2.html 必要的输出是:主机-1.2.3.4,端口-5678,资源-/path1/path2.html
这是我尝试过的方法:
例如: URL为-1.2.3.4:5678/path1/path2.html 必要的输出是:主机-1.2.3.4,端口-5678,资源-/path1/path2.html
这是我尝试过的方法:
#include <iostream>
#include <cstddef>
#include <string>
using namespace std;
int main()
{
string url="http://qwert.mjgug.ouhnbg:5678/path1/path2.html";
size_t found = url.find_first_of("://");
cout<<found<<endl;
string protocol=url.substr(0,found);
size_t found1 =url.find_first_of(":");
cout<<found1<<endl;
string host =url.substr(found+3,found1-found+1);
size_t found2 = url.find_first_of(":/");
string port1 =url.substr(found1+7,found2+found1-1);
string port =url.substr(found2+1);
cout<<protocol<<endl;
cout<<host<<endl;
cout<<port1<<endl;
cout<<port;
return 0;
}
我的期望结果是:
Protocol - http
Host - qwert.mjgug.ouhnbg
Port - 5678
Resource - path1/path2.html
但是我的结果是:
http:
qwert.mj
t.mjgug
//qwert.mjgug.ouhnbg:5678/path1/path2.html
我应该改变什么?
std::stringstream
中,并使用std::getline(stream, hoststr, ':')
和std::getline(stream, portstr, '/')
进行分割。流中的剩余部分只需要在前面添加 '/' 即可得到路径。 - user4581301