Implementing isalpha (const char * s) - how to improve this function?

I need a way to check if a string contains only alphabetic characters. Since I need a function several times in my program, I thought it was a good idea to include it in a function.

Here is my implementation:

int sisalpha(const char *s) {
    int result = 1;

    while (s++ != '\0') {
        result = isalpha(*s); // uses isalpha of <ctype.h>

        if (result == 0) {
            return result;
        }
    }

    return result;
}

What can I improve here? Would it also be useful to pass some size to avoid buffer overflows and allow substring checking?

+3
source share
6 answers

Use strspn .

Make a character set for verification, the alphabet in upper and lower case. If the value returned by strspn is the same as strlen, then this is all the alphabet.

+3
source

, . , :

int sisalpha(const char *s) {
    while (*s++ != '\0')
        if (!isalpha(*s))
            return 0;
    return 1;
}

, . , isalpha while, , :

int sisalpha(const char *s) {
    while (isalpha(*s))
      ++s;

    return *s == '\0';
}
+7
while ((*s|32)-'a'<26U) s++;
return !*s;
+5

meagar, s ++ while:

int sisalpha(const char *s) {
    while (*s != '\0')
        if (!isalpha(*s++))
            return 0;
    return 1;
}

int sisalpha(const char *s) {
    while (isalpha(*s))
        s++;
    return *s == '\0';
}
+3

, ascii :

int sisalpha(const char *s) {

        while(*s!='\0')
        {
            if((*s>='A'&&*s<='Z') || (*s>='a'&&*s<='z'))
                s++;
            else
                return 0;
        }
        return 1;
}
+3

, , .

, , -, ( , ).

Finally, it isalpha()accepts only arguments that can be represented as unsigned charor equal EOF. If your routine compiles on the platform where it is charsigned, you may violate this restriction.

Here is the version sisalpha()that fixes these problems (an empty string returns 1- I'm not sure if you want it or not):

int sisalpha(const char *s) {

    for (; *s != 0; ++s) {
        unsigned char c = *s;

        if (!isalpha(c)) return 0;
    }

    return 1;
}
+2
source

Source: https://habr.com/ru/post/1778406/


All Articles