A solution with tests
It is somewhat surprising that none of the answers here provide a test function to demonstrate how trim
behaves in corner cases. The empty string and strings composed entirely of spaces can both be troublesome.
Here is such a function:
#include <iomanip>
#include <iostream>
#include <string>
void test(std::string const& s)
{
auto const quote{ '\"' };
auto const q{ quote + s + quote };
auto const t{ quote + trim(s) + quote };
std::streamsize const w{ 6 };
std::cout << std::left
<< "s = " << std::setw(w) << q
<< " : trim(s) = " << std::setw(w) << t
<< '\n';
}
int main()
{
for (std::string s : {"", " ", " ", "a", " a", "a ", " a "})
test(s);
}
Testing the accepted solution
When I ran this on 2023-Aug-05 against the accepted answer, I was disappointed with how it treated strings composed entirely of spaces. I expected them to be trimmed to the empty string. Instead, they were returned unchanged. The if-statement is the reason why.
// Accepted solution by @Anthony Kong. Copied on 2023-Aug-05.
using namespace std;
string trim(const string& str)
{
size_t first = str.find_first_not_of(' ');
if (string::npos == first)
{
return str;
}
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last - first + 1));
}
Here is the output from my test:
s = "" : trim(s) = ""
s = " " : trim(s) = " "
s = " " : trim(s) = " "
s = "a" : trim(s) = "a"
s = " a" : trim(s) = "a"
s = "a " : trim(s) = "a"
s = " a " : trim(s) = "a"
Testing the "new and improved" version of trim
To make it work the way I wanted, I changed the if-statement.
While I was at it, I got rid of using namespace std;
, and changed the parameter name to s
. You know, because I could.
// "New and improved" version of trim. Lol.
std::string trim(std::string const& s)
{
auto const first{ s.find_first_not_of(' ') };
if (first == std::string::npos)
return {};
auto const last{ s.find_last_not_of(' ') };
return s.substr(first, (last - first + 1));
}
Now the test routine produces the output I like:
s = "" : trim(s) = ""
s = " " : trim(s) = ""
s = " " : trim(s) = ""
s = "a" : trim(s) = "a"
s = " a" : trim(s) = "a"
s = "a " : trim(s) = "a"
s = " a " : trim(s) = "a"