从字符串中提取子字符串的最佳和最快方法是什么
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
我想避免使用拆分之类的方法。
如果您绝对需要将结果作为字符串,则必须进行测量,但我怀疑任何事情都会比大多数事情快得多直观:
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()
我不知道他们在速度方面的实际表现,但这绝对值得一试。
相关文章:
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 在C++17中,引用const字符串的语义应该是什么
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 字符串上的 C++ push_back() 和 pop_back() 的 Kotlin 是什么?
- 这里的字符串函数是什么意思
- 将位字符串转储到二进制文件的最佳方法是什么
- 是什么使这个以'+'开头的字符串添加成为有效的语句?
- 在c++中,减号和加号对字符串的作用是什么
- 当我们已经有 char[] 时,在 c++ 中字符串的必要性是什么?
- C++ 将字符串数据包转换为 iphdr语言 - 字符串数据包的格式应该是什么?
- 这句话是什么意思?半 += 字符串(频率[i] / 2, i + 'a');
- Xamarin Android:在 C++ 中将字符串从 C# 封送到 Unicode 字符串的正确方法是什么?
- 使用c 中的sort()函数对字符串进行排序的最坏情况是什么是什么
- 字符串文本不能有外部链接的原因是什么?
- 当我打印字符串时,我不知道它是什么输出
- 字符串中单个字符作为数组的数据类型是什么
- 检查字符串是否与可能的输入之一匹配的最有效方法是什么?
- '|' scanf 格式字符串是什么意思
- 一个字符串开始另一个字符串是什么意思?c++
- 表示文件路径的guid字符串是什么?