How to Compare Characters in C++?
char in c is a keyword used for representing character data type. The memory size of char is 1 byte containing numbers, alphabets, and alphanumeric characters. We can compare the characters in C using 2 different ways:
- Comparison using ASCII values.
- Using the built-in function.
1. Using ASCII Values
As every character has a unique ASCII value. So, we can use this property for the comparison of characters. Let’s see with an example.
C
#include <stdio.h>
int main()
{
char first = 'a' ;
char second = 'b' ;
char third = 'a' ;
if (first == second)
printf ( "%c and %c are equal\n" ,
first, second);
else
printf ( "%c and %c are not equal\n" ,
first, second);
if (first == third)
printf ( "%c and %c are equal\n" ,
first, third);
else
printf ( "%c and %c are not equal\n" ,
first, third);
return 0;
}
|
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
char first = 'a' ;
char second = 'b' ;
char third = 'a' ;
if (first == second){
cout<<first<< " and " <<second<< " are equal \n" ;
}
else {
cout<<first<< " and " <<second<< " are not equal \n" ;
}
if (first == third)
cout<<first<< " and " <<third<< " are equal \n" ;
else
cout<<first<< " and " <<third<< " are not equal \n" ;
return 0;
}
|
Output
a and b are not equal
a and a are equal
2. Using strcmp Function – (Inbuilt function)
strcmp is a feature provided by <string> library in C. It’s a function used to compare strings but can be used to compare characters.
Syntax
strcmp( &ele1 , &ele2 ); // ele1 and ele2 are two elements to be compared
Parameters
- ele1 – represent element1 (string).
- ele2 – represent element2(string).
Both elements are inserted for comparison.
Return type: strcmp returns an integer value which is according to the result obtained after comparison.
- If both are equal returns 0.
- else returns -1.
Below is the C program to compare the characters using strcmp:
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char first[] = "b" ;
char second[] = "b" ;
char third[] = "a" ;
if ( strcmp (first, second) == 0)
printf ( "%s and %s are equal\n" ,
first, second);
else
printf ( "%s and %s are not equal\n" ,
first, second);
if ( strcmp (first, third) == 0)
printf ( "%s and %s are equal\n" ,
first, third);
else
printf ( "%s and %s are not equal\n" ,
first, third);
return 0;
}
|
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
char first[] = "b" ;
char second[] = "b" ;
char third[] = "a" ;
if ( strcmp (first, second) == 0)
cout<<first<< " and " <<second<< " are equal\n" ;
else
cout<<first<< " and " <<second<< " are not equal\n" ;
if ( strcmp (first, third) == 0)
cout<<first<< " and " <<third<< " are equal\n" ;
else
cout<<first<< " and " <<third<< " are not equal\n" ;
return 0;
}
|
Output
b and b are equal
b and a are not equal
Time complexity: O(1).
Auxiliary space: O(1).
Last Updated :
06 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...