C++没有直接函数来处理字符串首尾空字符,故这里使用 erase, find_first_not_of, find_last_not_of 这三个函数来处理
方法1:
string & Trim(string &str)
{
if(str.empty())
return str;
str.erase(0, str.find_first_not_of(" "));
str.erase(str.find_last_not_of(" ") + 1);
return str;
}
方法2:更严谨点,但需要加载 #include <tchar.h>
string & Trim_2(string &text)
{
if(!text.empty())
{
text.erase(0, text.find_first_not_of(_T(" \n\r\t"))); //删除开头空字符
text.erase(text.find_last_not_of(_T(" \n\r\t")) + 1); //删除尾部空字符
}
return text;
}
#include <iostream>
#include <string>
#include <tchar.h> // for "_T" declare
using namespace std;
string & Trim_2(string &text) //It's OK
{
if(!text.empty())
{
text.erase(0, text.find_first_not_of(_T(" \n\r\t"))); //删除开头空字符
text.erase(text.find_last_not_of(_T(" \n\r\t")) + 1); //删除尾部空字符
}
return text;
}
string & Trim(string &str)
{
if(str.empty())
return str;
str.erase(0, str.find_first_not_of(" "));
str.erase(str.find_last_not_of(" ") + 1);
return str;
}
int main()
{
string s1 = " the sky is blue! one parameter ll? "; //首尾各3个空格
string s2(s1);
cout<<"The string s1's length is = "<<s1.size()<<endl;
cout<<"The string s2's length is = "<<s2.size()<<endl;
cout<<"/**========**/"<<endl;
string s3 = Trim(s1);
cout<<"The s3 Result is="<<s3<<", and the string length is "<<s3.size()<<endl;
string s4 = Trim_2(s2);
cout<<"The s4 Result is="<<s4<<", and the string length is "<<s4.size()<<endl;
}