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:

  1. iterate through string: example: "my userid john17 , 4 digit pin 1234 secret."

  2. set boolean flag (isnumberonly=true)when find digit after space character , start caching word. please note flag false originally. example second '1' in example digit after space character. continue iterating,

  3. if find nondigit before reaching space set isnumberonly=false,

  4. 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

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -