How to Validate a String in C

How to Validate a String in C Language with Examples

In this article, I will discuss How to Validate a String in C Language with Examples. Please read our previous article discussing How to Count Vowels and Consonants in a String in C Language with Examples.

How to Validate a String in C Language?

Now, we will see how to validate a string. We have to check whether a given string is valid or not. Validating a string in C generally refers to checking if the string meets certain criteria or contains specific types of characters. The nature of the validation depends on your specific requirements. Common validations include checking for alphanumeric characters and specific patterns or ensuring the string doesn’t contain illegal characters.

Validating Characters in a String

Most of the time, while creating a login and an account, we have to mention a username and password. For most passwords, we find that a valid password is required. So, what is a valid password? Only alphabets or numbers are allowed. Special characters are not allowed. A similar thing we have to check in a string. Please observe the following string:

How to Validate a String in C Language with Examples

We have a string here that contains alphabets and numbers. It is a valid string. If any special character is there, then it is invalid. So, we have to check whether the string is valid or not.

There are two methods. One is a simple method that I am going to show you. The second method is using regular expressions. If you want to learn about regular expression, you can learn and use it in C / C++ programs. Now, let us follow the basic method.

In this method, we have to scan for this entire string and find whether each and every alphabet is valid or not. If any of the alphabets is invalid, then we should say it is invalid. So, let us write our separate functions. Let us modify our valid string to invalid by adding ‘@’ in the above string:

How to Validate a String in C Language with Examples

So, to perform this procedure, we have to check for each and every alphabet. The function ‘ValidateString’ will take a string as a parameter. It will return true or false, which means valid or not. It is valid if it returns 1. Otherwise, it is invalid if it returns ‘0’.

Program to Validate a String in C Language:
#include <stdio.h>
#include <stdlib.h>
int ValidateString (char *B)
{
        int i;
        for (i = 0; B[i] != '\0'; i++)
        {
               if (!(B[i] >= 65 && B[i] <= 90) && !(B[i] >= 97 && B[i] <= 122) && !(B[i] >= 48 && B[i] <= 57))
              {
                    return 0;
              }
       }
       return 1;
}
int main ()
{
        char *B = "Rahul@7928";
        int j;
        printf ("String is \"%s\"\n", B);
        if (ValidateString (B))
        {
              printf ("Valid String");
        }
        else
        {
             printf ("Invalid String");
        }
        return 0;
}

So, in this function, we haven’t done a lot of conditions. So, we have seen a validation function.

Output:

Validate a String Code in C Language

Checking if a String Contains Only Alphabetic Characters:

In the following example, isAlphabetic() checks if all characters in the string are alphabetic using isalpha().

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

int isAlphabetic(const char *str) {
    for (int i = 0; str[i] != '\0'; i++) {
        if (!isalpha((unsigned char)str[i])) {
            return 0; // false
        }
    }
    return 1; // true
}

int main() {
    char str[] = "HelloWorld";
    if (isAlphabetic(str)) {
        printf("The string is alphabetic.\n");
    } else {
        printf("The string is not alphabetic.\n");
    }
    return 0;
}
Checking if a String is a Valid Integer:

In the following example, isValidInteger() uses strtol() to convert the string to a long integer and checks various conditions to ensure the conversion is valid and within the range of an int.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>

int isValidInteger(const char *str) {
    char *endPtr;
    long value = strtol(str, &endPtr, 10);

    // Check for empty string, no conversion performed, or other errors
    if (str == endPtr || *endPtr != '\0' || errno == ERANGE || value > INT_MAX || value < INT_MIN) {
        return 0; // false
    }
    return 1; // true
}

int main() {
    char str[] = "12345";
    if (isValidInteger(str)) {
        printf("The string is a valid integer.\n");
    } else {
        printf("The string is not a valid integer.\n");
    }
    return 0;
}

In the next article, I will discuss How to Reverse a String in C Language with Examples. In this article, I explain How to Validate a String in C Language with Examples. I hope you enjoy this article, “How to Validate a String in C Language with Examples.” I would like to have your feedback. Please post your feedback, questions, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *