kolioi

Punctuation C++

Dec 18th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <sstream>
  5. #include <cctype>
  6. #include <map>
  7. #include <algorithm>
  8.  
  9. using namespace std;
  10.  
  11. bool is_punctuation(int ch)
  12. {
  13.     string punct_marks{ ".,!?;:-" };
  14.     return punct_marks.find(ch) != string::npos;
  15. }
  16.  
  17. int main()
  18. {
  19.     string line;
  20.     getline(cin, line);
  21.  
  22.     using WordInfo = pair<string, size_t>;
  23.     using WordData = vector<WordInfo>;
  24.     using WordMap = map<int, WordData>;
  25.  
  26.     WordMap data;
  27.     istringstream iss(line);
  28.     string s;
  29.     while (iss >> s)
  30.     {
  31.         size_t pos;
  32.         if(iss.good())
  33.             pos = static_cast<size_t>(iss.tellg());
  34.         else
  35.             pos = line.length();
  36.         pos -= s.length();
  37.  
  38.         s.erase(find_if(s.begin(), s.end(), [](int ch) { return is_punctuation(ch); }), s.end());
  39.  
  40.         data[s.length()].push_back(make_pair(s, pos));
  41.     }
  42.  
  43.     string result{ line };
  44.     for (auto w : data)
  45.     {
  46.         if (w.second.size() > 1)
  47.         {
  48.             for (size_t fwd = 0, bwd = w.second.size() - 1; fwd < bwd; ++fwd, --bwd)
  49.             {
  50.                 string left_str = w.second[fwd].first, right_str = w.second[bwd].first;
  51.                 if (left_str != right_str)
  52.                 {
  53.                     size_t len = w.first;
  54.                     result.replace(w.second[fwd].second, len, right_str);
  55.                     if (isupper(left_str[0]))
  56.                         left_str[0] = tolower(left_str[0]);
  57.                     result.replace(w.second[bwd].second, len, left_str);
  58.                 }
  59.             }
  60.         }
  61.     }
  62.  
  63.     result[0] = toupper(result[0]);
  64.     cout << result << endl;
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment