c++ - How to know if a word in a string has digits? -
the question have: how can tell if word in string has digit in or not?
what need do: write program reads in line of text , outputs line digits in integer numbers replaced 'x'.
for example:
my userid john17 , 4 digit pin 1234 secret.
it should become
my userid john17 , x digit pin xxxx secret.
notice how digits in john17 not affected.
the code have far:
#include <iostream> using namespace std; int main() { string str; int i; cout << "enter line of text: "; getline(cin, str); (i = 0; <= str.length(); i++) { if (str[i] >= '0' && str[i] <= '9') { str.at(i) = 'x'; } } cout << "edited text: " << str << endl; }
there plenty of methods can use. below of them:
1 - generic algorithm:
iterate through string: example:
"my userid john17 , 4 digit pin 1234 secret."
set boolean flag (
isnumberonly=true
)when find digit afterspace
character , start caching word. please note flagfalse
originally. example second'1'
in example digit afterspace
character. continue iterating,if find nondigit before reaching
space
setisnumberonly=false
,finish word. if
isnumberonly=true
print'x'
s (the number of characters in word cashed) else print cashed word, e.g.,17john
.
please note here john17
not affected @ all. 17john
not have been affected.
or
2 - if want use library , c++11 can read , test words 1 one with:
std::all_of(str.begin(), str.end(), ::isdigit); // c++11
for more details , examples:
http://en.cppreference.com/w/cpp/algorithm/all_any_none_of
or
3 - trick:
#include <iostream> #include <sstream> using namespace std; int main() { string str; cout << "enter line of text: "; getline(cin,str); istringstream iss(str); string word; string finalstr=""; while(iss >> word) { if(word.find_first_not_of( "0123456789" ) == string::npos) { for(int i=0; i<word.size(); i++) { finalstr+='x'; } } else { finalstr.append(word); } finalstr+=' '; } cout << "edited text: " << finalstr << endl; return 0; }
those examples.
hope helps!
Comments
Post a Comment