C++中String的Trim

  • StringUtil.h


#ifndef STRINGUTIL_H
#define STRINGUTIL_H

#include <string>

class StringUtil
{
    public:
        StringUtil();
        virtual ~StringUtil();

        static std::string& LTrim(std::string &s);
        static std::string& RTrim(std::string &s);
        static std::string& Trim(std::string &s);
    protected:
    private:
};

#endif // STRINGUTIL_H



  • StringUtil.cpp


#include "StringUtil.h"

StringUtil::StringUtil()
{
    //ctor
}

StringUtil::~StringUtil()
{
    //dtor
}

std::string& StringUtil::LTrim(std::string &s)
{
    return s.erase(0, s.find_first_not_of(" \t\n\r"));
}

std::string& StringUtil::RTrim(std::string &s)
{
    return s.erase(s.find_last_not_of(" \t\n\r")+1);
}

std::string& StringUtil::Trim(std::string &s)
{
    return RTrim(LTrim(s));
}




  • main.cpp
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>

#include "StringUtil.h"

using namespace std;

int main()
{
    cout << "Hello world Begin!" << endl;

    std::string s = "    sfasfd\n   ";
    std::cout << "*" << s << "*" << std::endl;
    StringUtil::Trim(s);
    std::cout << "*"<< s << "*" << std::endl;

    cout << "Hello world End!" << endl;
    return 0;
}
  • output


Hello world Begin!
*    sfasfd
   *
*sfasfd*
Hello world End!

Process returned 0 (0x0)   execution time : 0.017 s
Press any key to continue.



你可能感兴趣的:(C++中String的Trim)