2

I wrote the following c++ code which removes spaces from beginning and end of a string, But the problem with it is that it doesn't remove tabs, how may I fix that?

Plus, is there anything similar to tabs and spaces? (I am reading lines from file)

string trim_edges(string command) {
    const auto command_begin = command.find_first_not_of(' ');
    if (command_begin == std::string::npos)
        return "";

    const auto strEnd = command.find_last_not_of(' ');
    const auto strRange = strEnd - command_begin + 1;

    return command.substr(command_begin, strRange);
}
  • 1
    You might want to take a look at [What's the best way to trim std::string?](https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring) and [std::isspace](https://en.cppreference.com/w/cpp/string/byte/isspace) – t.niese Aug 04 '20 at 08:50

1 Answers1

8

find_first_not_of and find_last_not_of can also take a string as a set of characters to skip:

const auto command_begin = command.find_first_not_of(" \t");
const auto strEnd = command.find_last_not_of(" \t");
Botje
  • 26,269
  • 3
  • 31
  • 41
  • what the full code will look like? it seems you deleted return "" –  Aug 04 '20 at 08:34
  • Thanks, is there anything similar to spaces that need to e removed? like tabs and so on? –  Aug 04 '20 at 08:36
  • You could draw inspiration from [std::isspace](https://devdocs.io/cpp/string/byte/isspace) – Botje Aug 04 '20 at 08:40
  • @daniel For ASCII you could probably remove all chars `<= ' '` - otherwise, `"\a\b\f\n\r\t\v "` - See [Escape sequences](https://en.cppreference.com/w/cpp/language/escape) – Ted Lyngmo Aug 04 '20 at 08:42
  • @TedLyngmo what are those \a\b they aren't mentioned –  Aug 04 '20 at 09:38
  • 1
    They are mentioned in the link @TedLyngmo posted. – Botje Aug 04 '20 at 09:44