user3898993
user3898993

Reputation: 21

How to check if string matches pattern C

How to check if my string/char array starts with letter and is followed by 10 number in C? for eg. is it A1234567890 ? Are there any useful functions?

Upvotes: 0

Views: 3335

Answers (3)

user3437460
user3437460

Reputation: 17454

int main()
{
    char str[MAXSTR] = "A1234567890";
}

int isFormat(char str[MAXSTR])
{
    int len = strlen(str);
    int x=0, result=0;

    if(str[x] >= 'A' && str[x] <= 'Z')
    {
        for (x=1; x<len; x++)
            if(str[x] >= '0' && str[x] <= '9')
                result = 1;
            else
                return 0;
    }
    return result;
}

You can write your own function to check that. This is just one of the example. You can use the isalpha() function, but you may need to include <ctype.h>. isalpha() takes in a char.

Upvotes: 1

rullof
rullof

Reputation: 7424

You need to check the length of the string then the first character and finally the following 10 characters:

int check_string(char *str)
{
    if (str == NULL)
    {
        return 0;
    }

    if (strlen(str) < 11)
    {
        return 0;
    }

    if (!isalpha(str[0]))
    {
        return 0;
    }

    int i;

    for (i = 1; i < 11; i++)
    {
        if (!isdigit(str[i]))
        {
            return 0;
        }
    }

    return 1;
}

Upvotes: 0

Anonymous
Anonymous

Reputation: 2172

bool Test(const char* str)
{
    return str && isalpha(str[0]) && strspn(str+1,"0123456789")==10 /*&& str[11]==0*/;
}

Upvotes: 4

Related Questions