Comparing characters in c++

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are almost always ASCII codes, but other encodings are allowed. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as this on an ASCII system.

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

Note that even if ASCII is not required, this function will work because C requires that the digits are in consecutive order:

int isdigit(char c) {
    if(c >= '0' && c <= '9') 
        return 1;
    return 0;
} 

Home » C solved programs

In this code snippet/program/example we will learn how to compare two characters in c programming language?

Here we will implement this program “c program to compare two characters” using two methods. First will be simple method in which we will take two characters and compare them, and second we will create a user define function that will take two arguments and returns 0 or -1.

This program will read two character values from the user and compare them, if the characters are equal program will print “Characters are equal” and if characters are not equal, program will print “Characters are not equal”.

We will also compare characters using user define function, function name will be compareCharacters(). This function will take two characters as arguments. If characters are equal function will return 0 otherwise function will return -1.

C Code Snippet/ Program - Compare Two Characters in C programming language

/*C - Program to compare two characters.*/
#include<stdio.h>
int main(){
	char c1,c2;
	
	printf("Enter two characters: ");
	scanf("%c %c",&c1,&c2); //space b/w %c and %c
	
	if(c1==c2)
		printf("Characters are equal.\n");
	else
		printf("Characters are not equal.\n");
	
	return 0;
}

Using user define function

#include<stdio.h>

char compareCharacters(char a,char b){
	if(a==b)
		return 0;
	else
		return -1;
}

int main(){
	char c1,c2;
	
	printf("Enter two characters: ");
	scanf("%c %c",&c1,&c2); //space b/w %c and %c
	
	if(compareCharacters(c1,c2)==0)
		printf("Characters are equal.\n");
	else
		printf("Characters are not equal.\n");
	
	return 0;
}

Output

    First run:
    Enter two characters: x x 
    Characters are equal. 

    Second run:
    Enter two characters: x y 
    Characters are not equal.

Learn about String Comparison in C.

Overview

In this article, we are going to discuss string comparison in C. We can compare two strings in C using a variety of approaches, including the string library function strcmp(), without a function, pointers, and recursion.

Scope

  • In this, article we will discuss the program of string comparison in C using string library function, without using string library function, using pointers, and using recursion.
  • In this article, we will discuss possible return values by the string library function.

Introduction

Ever wondered how the websites check if the passwords match when you sign up or how the software detects if there’s any plagiarism, or how the spam filtering in your mail works?

There is one solution to all the above things - String Comparison.

Comparing characters in c++

Comparing two strings or string comparison in C involves finding out if they are the same or not. This is done by using some built-in function or comparing the strings character by character to determine if they are equal. In case they are not equal, we can also analyze and find out which string is lexicographically (lexicographic order means dictionary order, that is, the words which start from 'a' come before the words that start with 'b' and the earlier is lexicographically smaller than the later, we'll see about this later in the article) larger than the other by the various methods of string comparison in C.

There are four methods for string comparison in C.

  • String comparison by using strcmp() String Library function.
  • String comparison without using strcmp() function .
  • String comparison by using pointers.
  • String comparison by using recursion.

String comparison by Using String Library Function

The string library functions are pre-defined in string.h header file used to do operations on the strings. strcmp() function is used to compare two strings. The strcmp() function takes two strings as input and returns an integer result that can be zero, positive, or negative.

The strcmp() function compares both strings characters. If both strings have the same character at the same index till all of the characters have been compared or the pointer reaches the null character '\0' in both strings then we can say that both strings are equal.

Syntax of the strcmp() Function

int strcmp (const char* str1, const char* str2);  

In the syntax above, two arguments, str1 and str2, are passed as strings and the return type is int, indicating that strcmp() gives an integer value.

Possible Return Values from the strcmp() Function

Return ValueDescription
0 Returns 0, When both strings are exactly the same.
<0 The function will return a negative number if the ASCII value of a character in the first string is smaller than the ASCII value of a character in the second string.
>0 The function will return a positive value if a character's ASCII value in the first string is bigger than a character's ASCII value in the second string.

Example

#include <stdio.h>  
#include<string.h>  
int main()  
{  
   char str1[50];  // declaration of char array  
   char str2[50];  // declaration of char array  
   int value; // declaration of integer variable  
   
   printf("Enter the first string : ");  
   scanf("%s",str1);  
   printf("Enter the second string : ");  
   scanf("%s",str2);  
   
   // comparing both the strings using strcmp() function  
   value = strcmp(str1,str2);  
   if(value == 0)  
   printf("strings are same");  
   else  
   printf("strings are not same");  
   return 0;  
}  

Output:

Enter the first string : scaler
Enter the second string : interviewbit
strings are not same

Analysis of the Program

  • We've declared two char arrays, str1, and str2, respectively then take input for them.
  • The strcmp() function, is used to compare the strings (str1,str2). The strings str1 and str2 will be compared using this function. If the function returns a value 0, it signifies that the strings are equal otherwise, strings are not equal.

String Comparison without Using strcmp() Function

String comparison in C is also possible by using without strcmp() function. We could compare the two strings by traversing each index using a loop and comparing each character one by one.

#include <stdio.h>  
int compareTwoString(char[],char[]);  
int main()  
{  
   char str1[50]; // declaration of char array  
   char str2[50]; // declaration of char array
   
   printf("Enter the first string : ");  
   scanf("%s",str1);  
   
   printf("Enter the second string : ");  
   scanf("%s",str2);  
   
   int c= compareTwoString(str1,str2); // calling compareTwoString() function  
   if(c==0)  
   printf("strings are same");  
   else  
   printf("strings are not same");  
  
   return 0;  
}  
  
// Comparing both the strings.  
int compareTwoString(char a[],char b[])  
{  
    int flag=0,i=0;  // integer variables declaration  
    while(a[i]!='\0' &&b[i]!='\0')  // while loop  
    {  
       if(a[i]!=b[i])  
       {  
           flag=1;  
           break;  
       }  
       i++;  
    } 
    if(a[i]!='\0'||b[i]!='\0')
       return 1;
    if(flag==0)  
    return 0;  
    else  
    return 1;  
}  

Output:

Enter the first string : coding
Enter the second string : debugging
strings are not same

Explanation:

  • In the code example, We've declared two char arrays and are taking user input as strings.
  • We've built a compareTwoString() function that takes two user input strings as an argument and compares character by character using a while loop. If the function returns 0, then the strings are equal otherwise, strings are not equal.

String Comparison by Using Pointers

String comparison in C also possible by using pointers. In this approach, we use pointers to traverse the strings and then compare the characters pointed by the pointer.

#include<stdio.h>
int compareTwoString(char *, char *);
int main()
{
    char str1[50]; // declaration of char array
    char str2[50]; // declaration of char array
    
    printf("Enter the first string : ");
    scanf("%s", str1);
    printf("\nEnter the second string : ");
    scanf("%s", str2);
    
    int compare = compareTwoString(str1, str2); // calling compareTwoString() function.
    if (compare == 0)
        printf("strings are equal");
    else
        printf("strings are not equal");
    return 0;
}
// Comparing both the strings using pointers
int compareTwoString(char *a, char *b)
{
    int flag = 0;
    while (*a != '\0' && *b != '\0') // while loop
    {
        if (*a != *b)
        {
            flag = 1;
        }
        a++;
        b++;
    }
 if(*a!='\0'||*b!='\0')
       return 1;
    if (flag == 0)
        return 0;
    else
        return 1;
}

Output:

Enter the first string : Scaler
Enter the second string : Scaler
strings are equal

Explanation:

  • In the code example, We’ve declared two char arrays str1 ,str2 and then take input for them.
  • A compareTwoString() function has been defined, which takes two char pointers as an argument. The address of str1 is held by the 'a' pointer, whereas the address of str2 is held by the 'b' pointer. We've constructed a while loop inside the function that will run until the pointer a or b does not reach a null character.

Using Recursion

We can use recursion to compare two strings, so we'll calculate the lengths of both strings and the compareTwoString function will keep calling itself until the condition becomes false.

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

int compareTwoString(char str1[], char str2[])
{
    static int i = 0; // store the current index we are at in string
    
    // calculating the length of str1
    int l1 = strlen(str1);
    
    //calculating the length of str2
    int l2 = strlen(str2);
    static int c = 0; // store number of equal characters at same index 
    

    // if the length of both strings are not equal then it will return as 0
    if (l1 != l2)
    {
        return 0;
    }
    
    // if value of i is less than length of str1 
    // then their are still more characters left to compare
    else if (i < l1)
    {
        if (str1[i] == str2[i])
            c++; // count number of equal characeter at same index
        i++;
        compareTwoString(str1, str2);
    }
    
    if (c == i)
    {
        return 1;
    }
        return 0;
    
}

int main()
{
    // taking two input as char array
    char str1[50], str2[50], c;

    printf("Enter first string: ");
    
    //taking input for str1
    fgets(str1, 50, stdin);

    printf("Enter second string: ");
    
    //taking input for str2
    fgets(str2, 50, stdin);

    c = compareTwoString(str1, str2);
    if (c)
    {
        //this statement will be printed if both strings are equal
        printf("strings are equal");
    }
    else
    {
        //this statement will be printed if both strings are not equal
        printf("strings are not equal");
    }

    return 0;
}

Output:

Enter first string: code
Enter second string: code
strings are equal

Explanation:

  • In the code example, We’ve declared two char arrays str1 ,str2 and take input for them.
  • A compareTwoString() calculates the length of both string using strlen() function.
  • The compareTwoString() function will return 0 if the lengths of both strings are not equal.
  • If the lengths of both strings are equal then we will compare str1[i] with str2[i] and if str1[i] equals str2[i] we will increase the value of c and i. then compareTwoString(str1, str2) keeps calling itself until i < l1 is false.
  • compareTwoString() function gives 1 if c is equal to i as c counts the number of equal characters at the same index. If c becomes equal to i this specify strings are equal.
  • compareTwoString() function returns 0 if strings are not equal otherwise 1 if strings are equal.

Conclusion

  • A string is a group of characters and the direct comparison of two strings is not possible in C.
  • We can compare two strings in C using a variety of approaches.
  • The two strings to be checked must be compared character by character.
  • We can compare two strings using strcmp() string library function which returns 0 if two strings are not equal.
  • We can compare two strings without string library function also using loops.
  • We can also compare two strings using pointers or recursion.

Can C compare two characters?

We can compare two strings in C using a variety of approaches. The two strings to be checked must be compared character by character. We can compare two strings using strcmp() string library function which returns 0 if two strings are not equal.

Can I use == to compare characters?

Yes, char is just like any other primitive type, you can just compare them by == .

Do you use == or .equals for char?

Because char is a primitive type and does not implement equals , == compares char values directly in this case, where as String is an object. So for object comparison, the equality operator is applied to the references to the objects, not the objects they point to.

Can I use == to compare strings in C?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.