C++ with the substr of function to eliminate the space before and after the solution

  • 2020-04-01 23:39:01
  • OfStack

I recently did a problem where I ran into the details of eliminating Spaces before and after strings. There seems to be a string function in Java called trim() that eliminates whitespaces after strings. For c++, look up a reference to a c++ standard library Boost, which is easy to fix, but to download, set the environment variables, so don't do it. Of course, regular expressions can also be used for matching, but they all seem overkill. Why don't we just use the substr() function, and string has properties like find_last_not_of, find_first_not_of, and so on, and that's enough for us.

#include <iostream> 
#include <vector> 
#include <string> 
#include <fstream> 
using namespace std;
//Read each line from the file, and then eliminate the space before and after it into a new string.
int main()
{
    string newstring = "";
    vector<string> str;
    ifstream fin("a.txt");
    string line;
    while (getline(fin, line))
        str.push_back(line);
    for (unsigned i = 0; i < str.size(); i++)
    {
        newstring += str[i].substr(str[i].find_first_not_of(" "),str[i].find_last_not_of(" ")-str[i].find_first_not_of(" ")+1);
    }
    cout<<newstring<<endl;
    return 0;
}


Related articles: