post4dirk
post4dirk

Reputation: 313

C++ Check that in a string only exist following characters

The valid charaters are

// ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/

#include <iostream>
#include <string>

using namespace std;

int main();
{
  bool bIsValid = true;

  // test characters
  string strCheck("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/");
  string s("foo@?+baa") ; // should bring a "false" because of the "@?+" characters

  string::const_iterator it = strCheck.begin();

   // this is NOT a clever soulution has anybody a better idea ?   
   while (s.find(*it) != string::npos) 
   {
     ++it;

     if(!s.find((*it))
     {
       bIsValidKey = false;
       break;
     }

   }

cout << "Is Valid: " << bIsValid << endl ;

}

My problem is how can a get the first charater after the iteratorpoint to compare with the allowed charactes. I need something like (*it).first_charater_after to solve the problem.

Dos anybody has an other idea to check that in the string only exists a defined number of charaters?

Upvotes: 0

Views: 226

Answers (3)

Chris Drew
Chris Drew

Reputation: 15334

#include <iostream>
#include <string>

int main() {
  bool bIsValid = true;

  // test characters
  std::string strCheck("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/");
  std::string s("foo@?+baa") ; // should bring a "false" because of the "@?+" characters

  if (s.find_first_not_of(strCheck) != std::string::npos)
    bIsValid = false;

  std::cout << "Is Valid: " << bIsValid << std::endl ;
}

Upvotes: 0

DrD
DrD

Reputation: 439

Try this:

#include <iostream>
#include <string>
#include <regex>

using namespace std;

int main()
{
  bool bIsValid = true;

  string s("GHHbaa111__") ; // Add/remove other characters

    regex r("^[[:alnum:]_]*$");

    if (regex_match(s,r)) {
        cout << "Valid string" << endl;
    } else {
        cout << "Invalid string" << endl;
    }

 }

Upvotes: 0

Alan Stokes
Alan Stokes

Reputation: 18964

Use string::find_first_not_of?

Upvotes: 2

Related Questions