我正在尝试编写一个C++函数,将std::string包含URL的URL拆分为其组件.我需要将组件复制到这个结构中:
typedef struct urlstruct {
string protocol;
string address;
string port;
string page;
} urlstruct;
Run Code Online (Sandbox Code Playgroud)
这是迄今为止的功能:
int parseAnnounce2(string announce, urlstruct *urlinfo){
int i;
if(announce.find("://") != string::npos){
// "://" found in string, store protocol
for(i = 0; i < announce.find("://"); i++){
}
} else {
// No "://" found in string
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我需要将'://'序列之前的字符复制到urlinfo->协议字符串中.这样做的好方法是什么?
我知道我无法使用以下代码行分配它,因为协议字符串尚未初始化为包含该内存.
urlinfo->protocol[i] = announce[i];
Run Code Online (Sandbox Code Playgroud)
使用std::string::assign.这应该工作:
if (announce.find ("://") != std::string::npos)
urlinfo->protocol.assign (announce, 0, announce.find ("://"));
else
//not found, handle
Run Code Online (Sandbox Code Playgroud)
或者,如果要将find变量的结果存储为不计算/输入两次,您也可以这样做:
std::string::size_type foundPos = announce.find ("://");
if (foundPos != std::string::npos)
urlinfo->protocol.assign (announce, 0, foundPos);
else
//not found, handle
Run Code Online (Sandbox Code Playgroud)