Skip to content

Instantly share code, notes, and snippets.

@dyigitpolat
Created April 13, 2022 15:51
Show Gist options
  • Save dyigitpolat/eb7482b1cf2a1e3b1e9b88d188866efa to your computer and use it in GitHub Desktop.
Save dyigitpolat/eb7482b1cf2a1e3b1e9b88d188866efa to your computer and use it in GitHub Desktop.
remove trailing spaces
#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