从字符串中提取子字符串的最佳和最快方法是什么?

时间:2012-01-10 09:46:23

标签: c++

从字符串中提取字符串的最佳和最有效的方法是什么?我需要这个操作成千上万次预制件。

我有这个字符串,我想提取URL。 URL始终位于“url =”子字符串之后,直到字符串结尾。例如:

http://foo.com/fooimage.php?d=AQA4GxxxpcDPnw&w=130&h=130&url=http00253A00252F00252Fi1.img.com00252Fvi00252FpV4Taseyww00252Fhslt.jpg

我需要提取

http00253A00252F00252Fi1.img.com00252Fvi00252FpV4Taseyww00252Fhslt.jpg

我想避免使用split等。

4 个答案:

答案 0 :(得分:5)

如果您绝对需要将结果作为字符串,则必须进行测量, 但我怀疑任何事情都会比最快的要快 直观的:

std::string
getTrailer( std::string const& original, std::string const& key )
{
    std::string::const_iterator pivot
        = std::search( original.begin(), original.end(), key.begin(), key.end() );
    return pivot == original.end()
        ? std::string()  // or some error condition...
        : std::string( pivot + key.size(), original.end() );
}

然而,最快的方法可能是根本不提取字符串, 但要简单地将它保存为一对迭代器。如果你需要这么多, 可能值得定义一个Substring类来封装它。 (我发现这个变量非常有效 解析。)如果你这样做,不要忘记迭代器会 如果原始字符串消失则变为无效;一定要转换 在此之前你想要保留的任何东西。

答案 1 :(得分:2)

std::string inStr;

//this step is necessary
size_t pos = inStr.find("url=");

if(pos !=  std::string::npos){
  char const * url = &inStr[pos + 4];
  // it is fine to  do any read only operations with url
  // if you would apply some modifications to url, please make a copy string
}

答案 2 :(得分:0)

您可以使用std::string::find()

如果它是一个char *而不仅仅是将指针移动到“url =”

之后的位置
yourstring = (yourstring + yourstring.find("url=")+4 );

我想不出更快的事情......

答案 3 :(得分:0)

您还可以查看boost库。 例如boost::split()

我不知道他们在速度方面的表现如何,但绝对值得一试。