devxlogo

Use the Count Algorithm to Perform Simple Validation on Strings

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 #include #include 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 

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.

devx-admin

Share the Post: