Thangaraj
Thangaraj

Reputation: 3184

How can you strip non-ASCII characters from a string? in c++

How can you strip non-ASCII characters from a string?

I like to know how we can achieve this in c++

Upvotes: 2

Views: 6551

Answers (3)

Pete
Pete

Reputation: 4812

Maybe something like:

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());

Its nicer to define a reusable function for the erase-remove idiom

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());

Upvotes: 4

bjackfly
bjackfly

Reputation: 3336

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);
    }
  }
}

Upvotes: 0

cprogrammer
cprogrammer

Reputation: 5675

Strip everything that is greater than 127, or see http://www.asciitable.com/ and create a more specific range

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

Upvotes: -1

Related Questions