std::string trim(std::string& str)
{
if(str.empty())
return std::string();
size_t s,e;
for(s =0; s < str.length();s++){
if(!isspace(str.at(s)))
break;
}
for(e = str.length()-1; e >s ; e--){
if(!isspace(str.at(e)))
break;
}
if(s < e)
return str.substr(s, e - s + 1);
else
return std::string();
}
//3种情况,1空(empty) 2都是空格串(" ") 3正常的处理串(" test")
string trimLeft(const string& str)
{
string t = str;
for (string::iterator i = t.begin(); i != t.end(); i++)
{
if (!isspace(*i))
{
t.erase(t.begin(), i); //情况3的处理
break;
}
if(i == t.end() -1) //情况2
{
return "";
}
}
return t; //情况1,没有进入循环,直接return
}
string trimRight(const string& str)
{
//字符串没有
if (str.begin() == str.end())
{
return str;
}
string t = str;
for(string::iterator i = t.end() - 1;; --i)
{
if (!isspace(*i)) //正常循环
{
t.erase(i + 1, t.end());
break;
}
if(i == t.begin()) //字符串都是空格的时候
return "";
}
return t;
}
inline std::string trim_left(const std::string& source , const std::string& t = " ")
{
std::string str = source;
return str.erase(0, source.find_first_not_of(t));
}
inline std::string trim_right (const std::string& source, const std::string& t = " ")
{
std::string str = source;
return str.erase(str.find_last_not_of(t) + 1);
}
inline std::string trim(const std::string& source , const std::string& t = " ")
{
std::string str = source;
return trim_left(trim_right(str , t), t);
}