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

What is the best and fastest way to extract substring from string?

本文关键字:字符串 是什么 方法 提取 最佳      更新时间:2023-10-16

从字符串中提取字符串的最佳和最有效的方法是什么?我需要做成千上万次的预成型手术。

我有这个字符串,我想提取URL。URL总是在"URL="子字符串之后,直到字符串结束。例如:

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

我需要提取

http00253A00252F00252Fi1.img.com00252Fvi00252FpV4Taseyww00252Fhslt.jpg

我想避免使用拆分之类的方法。

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

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

然而最快的方法可能根本不提取字符串,而是简单地将其保持为一对迭代器。如果你非常需要这个,可能值得定义一个CCD_ 1类来封装它。(我发现,当解析。)如果你这样做,不要忘记迭代器会如果原始字符串消失,则变为无效;一定要转换在发生这种情况之前,您要保存到字符串中的任何内容。

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
}

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

如果是字符*,则只需将指针移动到"url="之后的位置

yourstring = (yourstring + yourstring.find("url=")+4 );

我想不出什么比这更快的了。。

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

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