Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C
Expertise: Beginner
Aug 21, 2003

Use the Count Algorithm to Perform Simple Validation on Strings

Sometimes it's necessary to perform a simple validation on a string to ensure, for example, that a string destined to be converted to a float contains only a single '.'.

If only simple validation of some kind is required, it's trivial to use the count algorithm to tally up suspected chars and report their numbers, as in:


#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{

	string n = "joebob@bigtrucks@com";
	string d = "12.34";

	int A = count(n.begin(), n.end(), '@');
	int C = count(d.begin(), d.end(), '.');

	cout << "There are " << A << " @ signs in JoeBob's email address!" <<
endl;
	cout << "There's " << C << " decimal point in JoeBob's checking balance."
<< endl;

	return 0;
}
It's nice to remember that strings are containers in the STL, just like a vector or list, and that their iterators refer to char pointers that can be counted, sorted, or partitioned just like any other collection of values.

Greg McClure
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap