noobtuts

C++ String Only-Consists-Of

Foreword

Only-consists-of checks if a string only consists of certain characters. A common usage of this can be found in many kinds of servers that handle user registrations(like MMORPG Servers).

Usually we want the username only to have numbers from 0-9 and letters from a-z and A-Z and not signs like ♣ § ® and so on. This can be easily checked if we have the right function in our library.

Implementation

We want our function to give us a Boolean return value, so we know if the text only consists of the certain characters or if it doesn't.

bool onlyConsistsOf(std::string& text, std::string& pattern)
{    
    // Both empty?
    if (text.length() == 0 && pattern.length() == 0) {
        return true;
    }

    // Text empty and pattern obviously not?
    if (text.length() == 0) {
        return false;
    }

    // Pattern empty and text obviously not?
    if (pattern.length() == 0) {
        return false;
    }
   
    // For each char in text
    for (unsigned int i = 0; i < text.length(); ++i)
    {
        // Check if it is one of the chars in the pattern
        bool valid = false;
        for (unsigned int j = 0; j < pattern.length(); ++j)
        {
            if (text.at(i) == pattern.at(j))
            {
                valid = true;
                break;
            }
        }

        if (!valid)
        {
            return false;
        }
    }

    return true;
}

The first parts of the algorithm need to handle some special cases that can happen with empty strings. The rest of it is plain simple, it just tests for each character in text if it's in the pattern or not.

Example

if (onlyConsistsOf("MyWord", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
{
    // only a-z and A-Z, so it returns true and we get here
}

if (onlyConsistsOf("MyWord$", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
{
    // '$' not in pattern, so we will never get here (it returns false)
}

Summary

With that function in our library we will have a less hard time developing secure servers. We can even wrap this function into things like this:

bool onlyConsistsOfazAZ(const std::string& test)
{
    return onlyConsistsOf(test, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
}

Very easy to understand and use. For a more powerful and slightly more complicated way to do things like that, please take a look at Regular Expressions.