如何从字符串中删除非ASCII字符?在c ++中

时间:2011-08-02 12:00:32

标签: c++ string strip

如何从字符串中删除非ASCII字符?

我想知道如何在c ++中实现这一目标

3 个答案:

答案 0 :(得分:4)

可能是这样的:

struct InvalidChar
{
    bool operator()(char c) const {
        return !isprint(static_cast<unsigned char>(c));
    }
};

std::string s;
HypoteticalReadFileToString(&s);
s.erase(std::remove_if(s.begin(),s.end(),InvalidChar()), s.end());

为擦除删除习惯用法定义可重用函数更好

template <typename C, typename P> 
void erase_remove_if(C& c, P predicate) {
    c.erase(std::remove_if(c.begin(), c.end(), predicate), c.end());
}

...

erase_remove_if(s, InvalidChar());

答案 1 :(得分:0)

void stringPurifier ( std::string& s )
{
    for ( std::string::iterator it = s.begin(), itEnd = s.end(); it!=itEnd; ++it)
    {
      if ( static_cast<unsigned int>(*it) < 32 || static_cast<unsigned int>(*it) > 127 )
      {
        (*it) = ' ';
      }
    }
}

void stringPurifier ( std::string& dest, const std::string& source )
{
  dest.reserve(source.size());
  for ( std::string::const_iterator it = source.begin(), itEnd = source.end(); it!=itEnd; ++it)
  {
    if ( static_cast<unsigned int>(*it) < 32 || static_cast<unsigned int>(*it) > 127 )
    {
      dest.push_back(' ');
    }
    else
    {
      dest.push_back(*it);
    }
  }
}

答案 2 :(得分:-1)

剥离大于127的所有内容,或查看http://www.asciitable.com/并创建更具体的范围

while (CrtChar)
{
  if (*CrtChar<35 || *CrtChar>127)
   *CrtChar = ' ';
}