C++ 删除字符串的首尾空字符

一种方法:

string CBasicExcel::RewriteTrim(string &str)
{
 int nLength = str.size();
 for (int i = 0; i < nLength; ++i)
 {
  if (str[i] == '\n')
  {
   str.erase(i);
  }
 }

 string::size_type pos = str.find_last_not_of(' ');
 if(pos != string::npos)
 {
  str.erase(pos + 1);
  pos = str.find_first_not_of(' ');
  if(pos != string::npos)
  {
   str.erase(0, pos);

  }
 }
 else
 {
  str.erase(str.begin(), str.end());
 }
 return str;
}

第二种方法:

void CCRAddressBookDlg::Trim(string &strTarget)
{
 if (strTarget != "")
 {
  string strBuff(strTarget);
  char space = ' ';
  strTarget.assign(strBuff.begin() + strBuff.find_first_not_of(space),
   strBuff.begin() + strBuff.find_last_not_of(space) + 1);
 }
}

posted on 2012-11-05 10:02  ssy黑桃a  阅读(1417)  评论(0编辑  收藏  举报