Question

Does anyone know of a better way to verify string format in C++ without using the C++11 regex class. Basically I have several strings in this type of format TAG1:VALUE, TAG2:VALUE, TAG1:VALUE, TAG2:VALUE

TAG1 and TAG2 are strings and VALUE is an integer value of various length

An example string would be: "PPS:112, FJ:543, PPS:76432, FJ:753" and so on.

I need a function that would verify that the format is exactly correct.

So far I am doing it with character by character verification. This seems tedious at best. Is there a better way that I am simply not aware of. Again I would like to avoid using regex from C++11 or any third party libraries unless I have to. I was mostly wondering if there is a better way to do this with just C++ and STL

Was it helpful?

Solution

Without using any third party libraries at all, not really. About the best you'll do using standard library components is something like the following:

#include <string>
#include <algorithm>

bool verify(const std::string& s)
{
    typedef std::string::size_type      size_type;
    typedef std::string::const_iterator cstr_it;

    size_type colon_index = s.find(":");

    if (colon_index == std::string::npos)
    {
        return false;
    }

    cstr_it letter_end = s.begin() + colon_index;
    bool valid_letter = std::all_of(s.begin(), letter_end, isupper);
    bool valid_number = std::all_of(letter_end, s.end(), isdigit);

    return valid_letter && valid_number;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top