Question

Is there a standard function in D to check if a string is alphanumeric? If not what'd be the most efficient way to do it? I'm guessing there are better ways than looping through the string and checking if the character is in between a range?

Was it helpful?

Solution

I don't think there's a single pre-made function for it, but you could compose two phobos functions (which imo is just as good!):

import std.algorithm, std.ascii;
bool good = all!isAlphaNum(your_string);

I think that does unnecessary utf decoding, so it wouldn't be maximally efficient but that's likely irrelevant for this anyway since the strings are surely short. But if that matters to you perhaps using .representation (from std.string iirc) or foreach(char c; your_string) isAlphaNum(c); yourself would be a bit faster.

OTHER TIPS

I think Adam D. Ruppe's solution may be a better one, but this can also be done using regular expressions. You can view an explanation of the regular expression here.

import std.regex;
import std.stdio;

void main()
{
    // Compile-time regexes are preferred
    // auto alnumRegex = regex(`^[A-Za-z][A-Za-z0-9]*$`);
    // Backticks represent raw strings (convenient for regexes)
    enum alnumRegex = ctRegex!(`^[A-Za-z][A-Za-z0-9]*$`);
    auto testString = "abc123";
    auto matchResult = match(testString, alnumRegex);

    if(matchResult)
    {
        writefln("Match(es) found: %s", matchResult);
    }
    else
    {
        writeln("Match not found");
    }
}

Of course, this only works for ASCII as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top