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 << "There are " << A << " @ signs in JoeBob's email address!" <

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.

See also  How IoT Tech Will Transform Logistics

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist