Batisk_AFF

Remove extra spaces from string

Feb 22nd, 2021 (edited)
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.56 KB | None | 0 0
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.     string s, s1 = "", s2 = ""; getline(cin, s);
  8.  
  9.     // v1
  10.     for (size_t i = 0; i < s.length(); ++i)
  11.     {
  12.         if ((s[i] != ' ') || ((s[i] == ' ') && (s1 != "") && (s1[s1.length()-1] != ' '))) s1 += s[i];
  13.     }
  14.  
  15.     // more readable v2
  16.     for (auto c : s)
  17.     {
  18.         if ((c != ' ') || ((c == ' ') && (s2 != "") && (s2.back() != ' '))) s2 += c;
  19.     }
  20.  
  21.     cout << "Input string: " << s << endl << "Output string v1: " << s1 << endl << "Output string v2: " << s2 << endl;
  22.  
  23.     return 0;
  24. }
Add Comment
Please, Sign In to add comment