Home > other >  How is this returning 0 , when it should be 1
How is this returning 0 , when it should be 1

Time:06-17

I'm trying to return 1 when the string has only alphabetical characters, but it is always returning 0, i think the problem is on the if, but i don't know why. Can someone explain, thanks.

int ft_str_is_alpha(char *str)
{
    int i = 0;

    while (str[i] != '\0')
    {
        if ((str[i] < 'a' && str[i] > 'z') || (str[i] < 'A' && str[i] > 'Z'))
        {
            return 0;
        }
        i  ;
    }
    return 1;
}

int main(void)
{
    char *str;

    str = "Hello World";
    printf("%s - %d\n", str, ft_str_is_alpha(str));
    str = "H1LLO W0RLD";
    printf("%s - %d\n", str, ft_str_is_alpha(str));
}

CodePudding user response:

It's because this composite condition will never be true:

if ((str[i] < 'a' && str[i] > 'z') || (str[i] < 'A' && str[i] > 'Z')) {

A char will not be able to be < 'a' and > 'z' at the same time (and the same goes for the capital letters).

What you want is likely:

if (!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') )) {

That is, you want to check if str[i] is not in the range ['a','z'] or ['A',Z'].

Alternative version:

if ((str[i] < 'a' || str[i] > 'z') && (str[i] < 'A' || str[i] > 'Z')) {

Which tests if str[i] is outside the range ['a','z'] and outside the range ['A','Z'].

Or just use the isalpha function:

if (!isalpha((unsigned char)str[i])) return 0; // if not alphabetic, return 0

Note that the (unsigned char) cast is necessary to avoid getting undefined behavior in case the char in str[i] is negative.

CodePudding user response:

You can try the following that includes the isalpha() function from ctype.h library:

#include <stdio.h>
#include <string.h>
#include <ctype.h>


int ft_str_is_alpha(char *str)
{
    int length = strlen(str);

    for(int i=0; i<length; i  ) {
        if (!isalpha( (unsigned char) str[i])) {
            return 0;
        }
    }
    return 1;
}

int main(void)
{
    char *str;

    str = "Hello World";
    printf("%s - %d\n", str, ft_str_is_alpha(str));
    str = "H1LLO W0RLD";
    printf("%s - %d\n", str, ft_str_is_alpha(str));
}

Also, your strings currently contain spaces, so this code will always return 0 when there are spaces.

If you want to ignore spaces add to your code:

(!isalpha(str[i]) && !isspace(str[i])

  •  Tags:  
  • c
  • Related