Advertisement
Ilya_Bykonya

Untitled

Oct 14th, 2022 (edited)
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. /*
  2. std::string_view -- класс, который позволяет обращаться
  3. к строке (std::string, массив char, или даже просто
  4. си-строка), не копируя сам объект. При этом можно
  5. обращаться к подстроке исходной строки.
  6.  
  7. В нём лежат: указатель (8 байт) и переменная
  8. типа size_t: length 4 (байта),
  9. указывающие, на какую именно подстроку указывает view.
  10. */
  11. size_t search(const std::string& source, const std::string& substring) {
  12. const auto hasher = std::hash<std::string_view>{};
  13. const auto substringHash = hasher(substring);
  14. for (size_t index = 0; index < source.size() - substring.size() + 1; ++index) {
  15. //Сначала посчитаем и сравним хеши. Это быстрее прямого сравнения
  16. auto view = std::string_view{ source };
  17. view.remove_prefix(index);
  18. view.remove_suffix(source.size() - substring.size() - index);
  19. if (substringHash != hasher(view)) {
  20. continue;
  21. }
  22.  
  23. //Если хеши равны - сравниваем строки, потому что коллизии никто не отменял
  24. bool isSuccess = true;
  25. for (size_t substringIndex = 0; substringIndex < substring.size(); ++substringIndex) {
  26. if (source[index + substringIndex] != substring[substringIndex]) {
  27. isSuccess = false;
  28. break;
  29. }
  30. }
  31.  
  32. if (isSuccess) {
  33. return index;
  34. }
  35. }
  36.  
  37. return static_cast<size_t>(-1);
  38. }
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement