Check if a String Contains Only Alphanumeric Characters in C

To check if a string contains only alphanumeric characters in C, you can iterate over each character and verify whether it is a letter or digit using functions like isalnum() from <ctype.h> or by manually comparing ASCII values. Below are several examples demonstrating different approaches to achieve this.


Example 1: Using isalnum() with a For Loop

In this example, we check if a string contains only alphanumeric characters by iterating through the string with a for loop and using the isalnum() function from <ctype.h>.

main.c

</>
Copy
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

int main() {
    char str[] = "Hello123";
    bool isAlnum = true;
    
    // Check each character using for loop and isalnum()
    for (int i = 0; str[i] != '\0'; i++) {
        if (!isalnum(str[i])) {
            isAlnum = false;
            break;
        }
    }
    
    if (isAlnum)
        printf("The string \"%s\" is alphanumeric.\n", str);
    else
        printf("The string \"%s\" is not alphanumeric.\n", str);
        
    return 0;
}

Explanation:

  1. We include the headers <stdio.h> for input/output, <ctype.h> for isalnum(), and <stdbool.h> for Boolean type support.
  2. A string str is declared with the value “Hello123”.
  3. A Boolean variable isAlnum is initialized to true to assume the string is alphanumeric.
  4. A for loop iterates through each character of the string until the null terminator '\0' is encountered.
  5. The isalnum() function checks if each character is either a letter or a digit; if any character fails the check, isAlnum is set to false and the loop exits.
  6. After the loop, the program prints whether the string is alphanumeric based on the value of isAlnum.

Output:

The string "Hello123" is alphanumeric.

Example 2: Using Pointer Iteration with isalnum()

In this example, we use a pointer to iterate through the string character by character and check each one using isalnum(). This approach demonstrates an alternative way to traverse a string in C.

main.c

</>
Copy
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

int main() {
    char str[] = "Test123!";
    bool isAlnum = true;
    char *ptr = str;
    
    // Use pointer iteration to check each character with isalnum()
    while (*ptr) {
        if (!isalnum(*ptr)) {
            isAlnum = false;
            break;
        }
        ptr++;
    }
    
    if (isAlnum)
        printf("The string \"%s\" is alphanumeric.\n", str);
    else
        printf("The string \"%s\" is not alphanumeric.\n", str);
        
    return 0;
}

Explanation:

  1. We include the necessary headers: <stdio.h>, <ctype.h>, and <stdbool.h>.
  2. A string str is declared with the value “Test123!” which contains an exclamation mark.
  3. A Boolean variable isAlnum is initialized to true.
  4. A pointer ptr is set to point to the beginning of the string.
  5. A while loop iterates through the string until the null terminator is reached, checking each character using isalnum(). If a non-alphanumeric character is found, isAlnum is set to false and the loop is terminated.
  6. The program then prints the result. In this case, the exclamation mark causes the string to be reported as not alphanumeric.

Output:

The string "Test123!" is not alphanumeric.

Example 3: Manually Checking ASCII Values

In this example, we manually check if each character is alphanumeric by comparing its ASCII value. This approach does not use isalnum() and helps you understand the underlying logic.

main.c

</>
Copy
#include <stdio.h>
#include <stdbool.h>

int main() {
    char str[] = "Data2025";
    bool isAlnum = true;
    
    // Iterate through the string and check ASCII values manually
    for (int i = 0; str[i] != '\0'; i++) {
        if (!((str[i] >= 'A' && str[i] <= 'Z') ||
              (str[i] >= 'a' && str[i] <= 'z') ||
              (str[i] >= '0' && str[i] <= '9'))) {
            isAlnum = false;
            break;
        }
    }
    
    if (isAlnum)
        printf("The string \"%s\" is alphanumeric.\n", str);
    else
        printf("The string \"%s\" is not alphanumeric.\n", str);
        
    return 0;
}

Explanation:

  1. We include <stdio.h> for input/output and <stdbool.h> for Boolean support.
  2. A string str is declared with the value “Data2025”.
  3. A Boolean variable isAlnum is initialized to true.
  4. A for loop iterates through each character until the null terminator is reached.
  5. Within the loop, the character is checked to see if it falls within the ASCII ranges for uppercase letters ('A' to 'Z'), lowercase letters ('a' to 'z'), or digits ('0' to '9'). If not, isAlnum is set to false and the loop terminates.
  6. The final result is printed, indicating that the string is alphanumeric.

Output:

The string "Data2025" is alphanumeric.

Conclusion

In this tutorial, we explored multiple approaches to determine if a string contains only alphanumeric characters in C. We covered:

  1. Using the isalnum() function with a for loop.
  2. Using pointer iteration combined with isalnum().
  3. Manually checking ASCII values to verify each character.