OneBite.Dev - Coding blog in a bite size

check if a string contains only alphanumeric characters in C

Code snippet on how to check if a string contains only alphanumeric characters in C

  int check_alphanumeric_string(char *str) 
  { 
      int len = strlen(str); 
  
      for (int i = 0; i < len; i++) { 
          if (!(str[i] >= 'a' && str[i] <= 'z') &&  
              !(str[i] >= 'A' && str[i] <= 'Z') &&  
              !(str[i] >= '0' && str[i] <= '9'))  
              return 0; 
      } 
  
      return 1; 
  } 

This code snippet checks if a given string only contains alphanumeric characters. It first gets the length of the string, then loops through each character of that string. As it checks each character, if it does not match the conditions for being an alphanumeric character, i.e. a lowercase letter from a-z, an uppercase letter from A-Z, or a number from 0-9, then it breaks the loop and returns 0. Otherwise, if the loop finishes without breaking, then it returns 1, to signify that the string is composed of only alphanumeric characters.

c