C ++ stl从字符串中提取子字符串的方法 - >到(像Javascript子串)

时间:2012-02-09 11:06:22

标签: c++ substring

我试图在功能上复制JavaScript的子字符串,通过给定子字符串from / to pos来从字符串中提取字符串。在我找到位置fromto后,我应该如何继续此功能?

std::string& UT::extractid(std::string& url)
{
    std::vector< std::string > tokens;
    std::string id = "";
    tokens = split(url,'v=');
    video_id = tokens.at(1);
    if(video_id.length()>2)
    {
        string::size_type ampersandPosition = video_id.find('&', 0 );
        if( ampersandPosition != string::npos ) {
            cout << "Found  at " << loc << endl;
        } else {
            cout << "Didn't find  " << endl;
        }
    }
    return video_id;
}

1 个答案:

答案 0 :(得分:2)

而不是

return video_id;

这样做:

size_t start = video_id.find_first_of("/");
if (start == string::npos) start = 0;
assert(ampersandPosition > start);
return video_id.substr(start, ampersandPosition - start);