Advertisement
chevengur

СПРИНТ № 8 | Эффективные линейные контейнеры | Урок 9: Можем лучше: совершенствуем парсинг строки 1

Jun 19th, 2024
558
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <cassert>
  2. #include <iostream>
  3. #include <string_view>
  4. #include <vector>
  5.  
  6. using namespace std;
  7.  
  8. vector<string_view> SplitIntoWordsView(string_view str) {
  9.     vector<string_view> result;
  10.     str.remove_prefix(std::min(str.find_first_not_of(" "), str.size()));
  11.  
  12.     while (!str.empty())
  13.     {
  14.         auto space = str.find(' ');
  15.         result.push_back(str.substr(0, space));
  16.         str.remove_prefix(std::min(str.find_first_of(" "), str.size()));
  17.         str.remove_prefix(std::min(str.find_first_not_of(" "), str.size()));
  18.     }
  19.  
  20.     return result;
  21. }
  22.  
  23. int main() {
  24.     assert((SplitIntoWordsView("") == vector<string_view>{}));
  25.     assert((SplitIntoWordsView("     ") == vector<string_view>{}));
  26.     assert((SplitIntoWordsView("aaaaaaa") == vector{ "aaaaaaa"sv }));
  27.     assert((SplitIntoWordsView("a") == vector{ "a"sv }));
  28.     assert((SplitIntoWordsView("a b c") == vector{ "a"sv, "b"sv, "c"sv }));
  29.     assert((SplitIntoWordsView("a    bbb   cc") == vector{ "a"sv, "bbb"sv, "cc"sv }));
  30.     assert((SplitIntoWordsView("  a    bbb   cc") == vector{ "a"sv, "bbb"sv, "cc"sv }));
  31.     assert((SplitIntoWordsView("a    bbb   cc   ") == vector{ "a"sv, "bbb"sv, "cc"sv }));
  32.     assert((SplitIntoWordsView("  a    bbb   cc   ") == vector{ "a"sv, "bbb"sv, "cc"sv }));
  33.     cout << "All OK" << endl;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement