How to use strcmp Function – (Inbuilt function) In C++
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
// C Program to compare the // characters using strcmp #include <stdio.h> #include <stdlib.h> #include <string.h> // Driver code int main() { // Declaring 2 characters char first[] = "b" ; char second[] = "b" ; char third[] = "a" ; // comparing first and // second character 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); // comparing second and // third character 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; // Driver code int main() { // Declaring 2 characters char first[] = "b" ; char second[] = "b" ; char third[] = "a" ; // comparing first and // second character if ( strcmp (first, second) == 0) cout<<first<< " and " <<second<< " are equal\n" ; else cout<<first<< " and " <<second<< " are not equal\n" ; // comparing second and // third character if ( strcmp (first, third) == 0) cout<<first<< " and " <<third<< " are equal\n" ; else cout<<first<< " and " <<third<< " are not equal\n" ; return 0; } |
b and b are equal b and a are not equal
Time complexity: O(1).
Auxiliary space: O(1).
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.