Как вы можете удалить не-ASCII символы из строки?в с ++ - PullRequest
2 голосов
/ 02 августа 2011

Как вы можете удалить не-ASCII символы из строки?

Мне нравится знать, как мы можем достичь этого в c ++

Ответы [ 3 ]

4 голосов
/ 02 августа 2011

Возможно что-то вроде:

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());
0 голосов
/ 14 декабря 2011
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);
    }
  }
}
0 голосов
/ 02 августа 2011

Уберите все, что больше 127, или посмотрите http://www.asciitable.com/ и создайте более конкретный диапазон

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