【问题标题】:Copying part of a std::string to another uninitialised string将 std::string 的一部分复制到另一个未初始化的字符串
【发布时间】:2012-07-21 16:57:58
【问题描述】:

我正在尝试编写一个 C++ 函数,它将包含 URL 的 std::string 拆分为其组件。我需要将组件复制到这个结构中:

typedef struct urlstruct {
    string protocol;
    string address;
    string port;
    string page;
} urlstruct;

这是目前为止的功能:

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;
}

我需要将 '://' 序列之前的字符复制到 urlinfo->protocol 字符串中。这样做的好方法是什么?

我知道我无法使用以下代码行分配它,因为协议字符串尚未初始化为包含该内存。

urlinfo->protocol[i] = announce[i];

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    使用std::string::assign。这应该有效:

    if (announce.find ("://") != std::string::npos)
        urlinfo->protocol.assign (announce, 0, announce.find ("://"));
    else
        //not found, handle
    

    或者,如果您想将 find 的结果存储在一个变量中以不计算/键入两次,您也可以这样做:

    std::string::size_type foundPos = announce.find ("://");
    if (foundPos != std::string::npos)
        urlinfo->protocol.assign (announce, 0, foundPos);
    else
        //not found, handle
    

    【讨论】:

    • 您可以通过将值存储在变量中来消除对 std::string::find() 的重复调用。
    • @Code-Guru,你可以,是的。不过,我认为编译器会解决这个问题。
    • 嗯...检查哪些编译器(如果有)优化了函数调用会很有趣。当然,我尽量不过度依赖编译器优化。
    • 为了优化 find 调用,编译器必须能够断言它没有副作用。
    【解决方案2】:

    std::string::insert 应该在这里完成工作:

    size_t pos = announce.find("://");
    if(pos != std::string::npos)
    {
        protocol.insert(0, announce, 0, pos);
    }
    

    【讨论】:

      【解决方案3】:

      另一种选择是使用std::string::substr()。您已经拥有此功能所需的所有信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-14
        • 2015-02-05
        • 2017-01-11
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多