In this section, we will write a helper function that identifies surrounding white space in a string and returns a copy without that, and then we are going to test it briefly.
- As always, the header includes and using directive come first:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
- Our function to trim whitespace surrounding a string takes a const reference to an existing string. It will return a new string without any surrounding whitespace:
string trim_whitespace_surrounding(const string &s)
{
- The std::string provides two handy functions, which help us a lot. The first is string::find_first_not_of, which accepts a string containing all the characters we want to skip over. This is, of course, whitespace, meaning the characters space ' ', tab 't', and new line, 'n'. It returns us the first non-whitespace character position. If there is only whitespace in the string, it returns string::npos. This means that there is only an empty string left if we trim whitespace from it. So, in such a case, let's just return an empty string:
const char whitespace[] {" tn"};
const size_t first (s.find_first_not_of(whitespace));
if (string::npos == first) { return {}; }
- We know now where the new string has to begin, but we don't yet know where it has to end. Therefore, we use the other handy string function string::find_last_not_of. It will return us the last character position in the string which is no whitespace:
const size_t last (s.find_last_not_of(whitespace));
- Using string::substr, we can now return the part of the string, which is surrounded by whitespace but without the white space. This function takes two parameters--a position in the string to begin with and the number of characters after this position:
return s.substr(first, (last - first + 1));
}
- That's it. Let's write a main function in which we create a string that surrounds a text sentence with all kinds of whitespace, in order to trim it:
int main()
{
string s {" tn string surrounded by ugly"
" whitespace tn "};
- We print the untrimmed and trimmed versions of the string. By surrounding the string with brackets, it's more obvious which whitespace belonged to it prior to trimming:
cout << "{" << s << "}n";
cout << "{"
<< trim_whitespace_surrounding(s)
<< "}n";
}
- Compiling and running the program yields us the output we expected:
$ ./trim_whitespace
{
string surrounded by ugly whitespace
}
{string surrounded by ugly whitespace}