Skip to main content
3 of 4
Fixed header misspelling, edit about double negation
esote
  • 3.8k
  • 2
  • 25
  • 44

Fastest way to Determine if C-Style String is Alphabetic

I'm looking for the fastest way to determine if a C-style string contains only alphabetic characters.

For this question, there are a few assumptions:

  1. strlen(c) > 0
  2. Strings are null-terminated
  3. Continuous character encoding from a-z and A-Z is not guaranteed, but likely.
  4. The string is not a null pointer, nor is the pointer its "default value".

Here is my attempt:

#include <stdbool.h>
#include <ctype.h>

bool stralpha(const char *c)
{
    bool alphabetic = true;

    while(*c)
        alphabetic &= !!isalpha(*c++);

    return alphabetic;
}

/* so gcc does not complain */
int main(void){}

To be clear: I know that any performance difference in such a function will be minimal at best. This is just for fun.

Edit: In my case, I was having issues with the function returning false even when c was purely alphabetic. That is why I use double negation !! on isalpha(), because it is not guaranteed to return consistently 0 or 1 per the standard.

esote
  • 3.8k
  • 2
  • 25
  • 44