[英]What is the best and fastest way to extract substring from string?
從字符串中提取字符串的最佳和最有效的方法是什么? 我將需要將該操作進行成千上萬次的預成型。
我有這個字符串,我想提取URL。 URL始終在“ url =”子字符串之后,直到字符串末尾。 例如:
http://foo.com/fooimage.php?d=AQA4GxxxpcDPnw&w=130&h=130&url=http00253A00252F00252Fi1.img.com00252Fvi00252FpV4Taseyww00252Fhslt.jpg
我需要提取
http00253A00252F00252Fi1.img.com00252Fvi00252FpV4Taseyww00252Fhslt.jpg
我想避免使用split等。
如果您絕對需要字符串形式的結果,則必須進行測量,但是我懷疑任何東西都將比最直觀的方法快得多:
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
類。 (我發現它的可變變體在解析時非常有效。)如果您采用這種方式,請不要忘記,如果原始字符串消失,則迭代器將變得無效。 確保在發生這種情況之前,將要保留的任何內容都轉換為字符串。
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()
:
如果它是一個char *,則不只是將指針移到“ url =”之后的位置
yourstring = (yourstring + yourstring.find("url=")+4 );
我想不出什么更快..
您還可以查看Boost庫。 例如boost :: split()
我不知道它們在速度方面的實際表現,但是絕對值得一試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.