Created
April 13, 2022 15:51
-
-
Save dyigitpolat/eb7482b1cf2a1e3b1e9b88d188866efa to your computer and use it in GitHub Desktop.
remove trailing spaces
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <cstddef> | |
void remove_trailing_spaces(std::string& str) | |
{ | |
bool trailing{false}; | |
int prev_begin{}; | |
int removed_spaces{}; | |
for(std::size_t i = 0; i < str.size(); ++i) | |
{ | |
if(str[i] == ' ') | |
{ | |
if(not trailing) | |
{ | |
prev_begin = i + 1 - removed_spaces; | |
trailing = true; | |
} | |
else | |
{ | |
removed_spaces++; | |
} | |
} | |
else | |
{ | |
trailing = false; | |
std::swap(str[prev_begin++], str[i]); | |
} | |
} | |
str.erase(str.size() - removed_spaces, removed_spaces); | |
} | |
int main() | |
{ | |
std::string str{"aaa bbbb c g"}; | |
remove_trailing_spaces(str); | |
std::cout << '"' << str << '"' << '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment