How to erase all non alphanumeric characters from a string?
Nov 25, 2014 at 9:01am UTC
I want to erase all non alphanumeric characters from a string. I've tried the following way using erase() function. But it erases all the characters from where it finds a non alphanumeric character.
If I input:
it. is? awesome!
It Prints:
it
But it should print:
itisawesome
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin,s);
for (int i=0; i<s.length(); i++)
{
if (!isalpha(s[i]))
s.erase(i);
}
cout<<s<<endl;
return 0;
}
Nov 25, 2014 at 9:10am UTC
1 2 3 4 5
for (string::iterator i = s.begin(); i != s.end(); i++)
{
if (!isalpha(s.at(i - s.begin())))
s.erase(i);
}
Nov 25, 2014 at 9:21am UTC
@shadowCODE
If I Input: it.. is?? awe!?some??..
It doesn't work.
It should print: itisawesome
Nov 25, 2014 at 9:27am UTC
1 2 3 4 5 6 7 8
for (string::iterator i = s.begin(); i != s.end(); i++)
{
if (!isalpha(s.at(i - s.begin())))
{
s.erase(i);
i--;
}
}
Nov 25, 2014 at 9:29am UTC
Your post specifies alphanumeric . If this is really what you want, you should use isalnum
instead of isalpha
Nov 25, 2014 at 9:34am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
int main()
{
const std::string str = "it. is? awesome!" ;
{
// simple
std::string a ;
for ( char c : str ) if ( std::isalnum(c) ) a += c ;
std::cout << a << '\n' ;
}
{
// complicated: after erasing, stay at the same position for the next char
// but cater to the erase having reduced the size of the string
std::string b = str ;
for ( std::size_t i = 0 ; i < b.size() ; ++i )
while ( !std::isalnum( b[i] ) && i < b.size() ) b.erase(i,1) ;
std::cout << b << '\n' ;
}
{
// erase(iterator) returns the iterator following the erased character.
// http://en.cppreference.com/w/cpp/string/basic_string/erase
std::string c = str ;
for ( std::string::iterator iter = c.begin() ; iter != c.end() ; )
if ( !std::isalnum(*iter) ) iter = c.erase(iter) ;
else ++iter ; // not erased, increment iterator
std::cout << c << '\n' ;
}
{
// erase-remove idiom https://en.wikipedia.org/wiki/Erase-remove_idiom
std::string d = str ;
d.erase( std::remove_if( d.begin(), d.end(), []( char c ) { return !std::isalnum(c) ; } ), d.end() ) ;
std::cout << d << '\n' ;
}
}
http://coliru.stacked-crooked.com/a/4de5c2f5b8b0d0ec
Nov 25, 2014 at 10:20am UTC
Thank you all! :)
Topic archived. No new replies allowed.