In this article, you will learn methods to compare strings in C++.
Strings in C++ can be compared using one of the following techniques:
String
strcmp()
function in C++C++ String
has built-in functions for manipulating data of String
type. The strcmp()
function is a C library function used to compare two strings in a lexicographical manner.
strcmp()
Syntaxchar
array of C-style String.strcmp()
compares the strings in a case-sensitive form as well.This function returns the following values according to the matching cases:
0
if both the strings are the same.< 0
(less than zero) if the value of the character of the first string is smaller as compared to the second string input.> 0
(greater than zero) when the second string is greater in comparison.strcmp()
Example 1Run the following code:
This will generate the following output:
strcmp(str_inp1, str_inp2)
results in -9
. The values of str_inp1
and str_inp2
are different.
strcmp()
Example 2Run the following code:
This will generate the following output:
strcmp(str_inp1, str_inp2)
results in 0
. The values of str_inp1
and str_inp2
are the same.
compare()
function in C++C++ has a built-in compare()
function to compare two strings.
compare()
SyntaxThe compare()
function compares two strings:
This function returns the following values according to the matching cases:
0
if both the strings are the same.< 0
(less than zero) if the value of the character of the first string is smaller as compared to the second string input.> 0
(greater than zero) when the second string is greater in comparison.compare()
Run the following code:
In this example, str_inp1
and str_inp2
are compared with compare()
:
Both the strings are the same lexicographically, so the function returns 0
.
compare()
Run the following code:
In this example, str_inp0
is compared to str_inp1
:
Then, str_inp0
is compared to str_inp2
:
This code directly compared a string with another input string to the compare()
function.
C++ Relational operators such as ==
(double equals) and !=
(not equals) can be helpful in the comparison of strings.
Check if two values are equal:
Check if two values are not equal:
==
operatorRun the following code:
Provide values for “String 1” and “String 2”:
The code will compare the two strings with ==
.
!=
operatorRun the following code:
Provide values for “String 1” and “String 2”:
The code will compare the two strings with !=
.
In this article, you learned methods to compare strings in C++. This included String
’s strcmp()
function, the built-in compare()
function, and relational operators (==
, !=
).
Continue your learning with more C++ tutorials.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
nicely explained!!
- manoj
This Was very educative
- Lyson Phiri