Advertisement
Shokedbrain

split line into sentence

Jun 7th, 2021
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4. #include <vector>
  5.  
  6. using std::cin;
  7. using std::cout;
  8. using std::endl;
  9. using std::string;
  10. using std::vector;
  11.  
  12. int count_words(string str)
  13. {
  14.     // кол-во слов = количество пробелов + 1
  15.     return std::count(str.begin(), str.end(), ' ') + 1;
  16. }
  17.  
  18. vector<string> sentence(const string inp)
  19. {
  20.     string str = inp;
  21.     // разбиваем строку на предложения
  22.     std::vector<string> result;
  23.     const string delimiter = ".";
  24.     size_t pos = 0;
  25.     string buf{};
  26.     // пока существует разделитель в предложении
  27.     while((pos = str.find(delimiter)) != string::npos)
  28.     {
  29.         // удаляем лишние пробелы в начале, если они существуют
  30.         if (str.at(0) == ' ')
  31.             buf = str.substr(1,pos);
  32.         else
  33.             buf = str.substr(0,pos);
  34.         // добавляем в вектор предложение
  35.         result.push_back(buf);
  36.         // удаляем из общей строки предложение
  37.         str.erase(0, pos + delimiter.length());
  38.     }
  39.     return result;
  40. }
  41.  
  42. int main()
  43. {
  44.     std::ifstream in("text.txt");
  45.     if (!in.is_open())
  46.     {
  47.         cout << "could not read the file. \n";
  48.         return -1;
  49.     }
  50.    
  51.     int count_of_words = 0;
  52.     cout << "enter count of words: ";
  53.     cin >> count_of_words;
  54.    
  55.     string buf{};
  56.     while(std::getline(in,buf))
  57.     {
  58.         vector<string> inp = sentence(buf);
  59.         for (const auto& sentence: inp)
  60.         {
  61.             if (count_words(sentence) == count_of_words)
  62.                 cout << sentence << endl;
  63.         }
  64.     }
  65.     in.close();
  66.     system("pause");
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement