简体   繁体   English

使用迭代器查找字符串中的子字符串

[英]Find substring in string with iterators

I have a substring defined by two iterators ( start and end ). 我有一个由两个迭代器( startend )定义的子字符串。 I need to check if this substring is present in another string. 我需要检查此子字符串是否存在于另一个字符串中。

Is there a standard library algorithm or string member I can use or adapt to do this without creating a whole new string object ( std::string(start, end) ) just for this purpose? 我是否可以使用标准标准的算法或字符串成员来执行此操作,而无需为此创建一个全新的字符串对象( std::string(start, end) )?

eg 例如

struct Substring
{
    std::string::const_iterator start, end;
};

auto found = std::contains(whole.begin(), whole.end(), substring.start, substring.end); // ???

std::search

bool found = 
    std::search(hay.begin(), hay.end(), needle.begin(), needle.end()) != hay.end();

You can use the std::string::find method: 您可以使用std::string::find方法:

auto found = (whole.find(&*substring.start, 0, substring.end - substring.start)
              != std::string::npos);

The advantage over std::search is that std::find works on strings and can be implemented using Boyer-Moore. std::search相比,优点是std::find可在字符串上运行,并且可以使用Boyer-Moore来实现。 Sadly, that is not how gcc's libstdc++ implements it. 可悲的是,这不是gcc的libstdc ++实现它的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM