Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- std::string_view -- класс, который позволяет обращаться
- к строке (std::string, массив char, или даже просто
- си-строка), не копируя сам объект. При этом можно
- обращаться к подстроке исходной строки.
- В нём лежат: указатель (8 байт) и переменная
- типа size_t: length 4 (байта),
- указывающие, на какую именно подстроку указывает view.
- */
- size_t search(const std::string& source, const std::string& substring) {
- const auto hasher = std::hash<std::string_view>{};
- const auto substringHash = hasher(substring);
- for (size_t index = 0; index < source.size() - substring.size() + 1; ++index) {
- //Сначала посчитаем и сравним хеши. Это быстрее прямого сравнения
- auto view = std::string_view{ source };
- view.remove_prefix(index);
- view.remove_suffix(source.size() - substring.size() - index);
- if (substringHash != hasher(view)) {
- continue;
- }
- //Если хеши равны - сравниваем строки, потому что коллизии никто не отменял
- bool isSuccess = true;
- for (size_t substringIndex = 0; substringIndex < substring.size(); ++substringIndex) {
- if (source[index + substringIndex] != substring[substringIndex]) {
- isSuccess = false;
- break;
- }
- }
- if (isSuccess) {
- return index;
- }
- }
- return static_cast<size_t>(-1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement