If you want to trim spaces at both ends with std::string class object, you can use
std::string::find_first_not_of[
^] and
std::string::string/find_last_not_of[
^.
A bit of logic and
std::string::substr[
^], you are able to create a function that will do the same as .NET
System::String::Trim[
^] function does for managed strings.
The code should look like this
(not tested):
using namespace std;
string trim(const string &source, const string &trim_chars)
{
size_t pos1 = source.find_first_not_of(trim_chars);
size_t pos2 = source.find_last_not_of(trim_chars);
if (pos1 == string::npos && pos2 == string::npos) { return source; }
if (pos1 == string::npos) { pos1 = 0; }
if (pos2 == string::npos) { pos2 = source.length(); }
size_t trimmed_length = pos2 - pos1;
return source.substr(pos1, trimmed_length);
}
string trim(const string &source)
{
string trim_chars(" \t\r\n"); return trim(source, trim_chars);
}
If you want to remove all spaces, then you might uses similar functions in a loop and construct a new string on the fly. Essentially, you would find first char that is not a space and next space after that and copy that part and then repeat until the remainding part of the string does not contains spaces anymore.