Trim whitespace from strings
It is common for input from users to include extraneous whitespace at one or both ends of a string. This can be problematic, so we often need to remove it. In this recipe, we'll use the string
class methods, find_first_not_of()
and find_last_not_of()
, to trim whitespace from the ends of a string.
How to do it…
The string
class includes methods for finding elements that are, or are not, included in a list of characters. We'll use these methods to trim string
:
- We start by defining
string
with input from a hypothetical ten-thumbed user:int main() { string s{" \t ten-thumbed input \t \n \t "}; cout << format("[{}]\n", s); ...
Our input has a few extra tab \t
and newline \n
characters before and after the content. We print it with surrounding brackets to show the whitespace:
[...