将std :: string的一部分复制到另一个未初始化的字符串

brn*_*nby 1 c++ string

我正在尝试编写一个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)

chr*_*ris 5

使用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)

  • 您可以通过将值存储在变量中来消除对std :: string :: find()的重复调用. (2认同)