Anuj Mattoo Anuj Mattoo - 1 year ago 67
C Question

How to check if String consist of numeric or alphabet in C

I need some help in Identifying the string. I have incoming string like this

it can vary from
sometimes it is
or any other text in between.Now what I have already done is I have parsed the numeric string and copied the integer value to a buffer. Here is the code for that.

char H1subbuff[10];

char *ptr;

if ((strncmp(rec,"*H1", 3) == 0) && (rec[9] == '#'))
memcpy(H1subbuff, &rec[3], 6 );
H1subbuff[6] = '\0';

H1Val = strtol(H1subbuff, &ptr, 10);

//Display H1VAL

Now my query is how can check if the String consist of Number or Alphabet. How can I check
data, so that I can compare. I need to do the same above process of parsing

Note :- The above two string doesn't have same string length.

Answer Source

like this:

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

bool validate_data(const char rec[], int *number, char text[]){
    *number = -1;//if invalid
    *text = 0;   //if invalid

    if(strncmp(rec, "*H1", 3) != 0) return false;//invalid header

    bool not_digit = false;
    int i, j = 0;
    for(i = 3; rec[i] && rec[i] != '#'; ++i){
        text[j++] = rec[i];
            not_digit = true;
    text[j] = 0;

    if(rec[i] != '#'){
        *text = 0;
        return false;//invalid footer
    if(not_digit == false){
        if(j != 6){
            *text = 0;//valid as text?
            return false;//invalid number format
        *number = atoi(text);
    return true;

int main(void){
    const char *test_data[] = {
        "*H1000000#","*H1999999#", "*H1123456#", "*H1FINE#", "*H1MED#",
        "*h123#", "**H1666666#", "*H2888888#", "*H1777#", "*H1555555"
    int number_of_data = sizeof(test_data)/sizeof(*test_data);
    char H1subbuff[10];
    int H1Val;

    for(int i = 0; i < number_of_data; ++i){
        printf("%s :\n", test_data[i]);
        if(validate_data(test_data[i], &H1Val, H1subbuff)){
            if(H1Val >= 0)
                printf("value is %d(%s)\n", H1Val, H1subbuff);
                printf("text is %s\n", H1subbuff);
        } else {
            printf("invalid format\n");
    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download