Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5. using namespace std;
  6. //Функция разбивает строку на слова и складывает в вектор
  7.  
  8. //Короче на итераторах он работает, даже если в конце нет пробела!!! Хорошо
  9. //Однако мне кажется, что реализацию на итераторах можно упростить она громоздкая
  10.  
  11. //На итераторах
  12. vector<string> SplitIntoWordsIt(const string& s)
  13. {
  14.     string word;
  15.     vector<string> strs;
  16.     auto Itbeg = s.begin();
  17.     auto Itend = s.end();
  18.     while(Itbeg<=Itend)
  19.     {
  20.         if (Itbeg == Itend)
  21.         {
  22.             strs.push_back(word);
  23.             word.clear();
  24.             break;
  25.         }
  26.         else if (*Itbeg != ' ')
  27.         {
  28.             word.push_back(*Itbeg);
  29.         }
  30.         else if (*Itbeg == ' ')
  31.         {
  32.             strs.push_back(word);
  33.             word.clear();
  34.         }
  35.         Itbeg++;
  36.     }
  37.     return strs;
  38. }
  39.  
  40.  
  41. //Без итераторов и нужен пробел в конце
  42. vector<string> SplitIntoWords(const string& s)
  43. {
  44.     string word;
  45.     vector<string> strs;
  46.     for(const auto& ch : s)
  47.     {
  48.         if(ch != ' ')
  49.         {
  50.             word.push_back(ch);
  51.         }
  52.         else if(ch == ' ')
  53.         {
  54.             strs.push_back(word);
  55.             word.clear();
  56.         }
  57.     }
  58.     return strs;
  59. }
  60.  
  61.  
  62. int main()
  63. {
  64.     vector<string> strvec = SplitIntoWordsIt("Do you think we are animals");
  65.    
  66.     for(auto i : strvec)
  67.     {
  68.         cout << i << " ";
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement