This post will discuss how to compare two strings in C++.

1. Using string::compare

The string::compare function compares the value of a string with the specified sequence of characters. The specified sequence can be another string or a pointer to a character array. It returns an integer value indicating the relationship between the two strings.

A zero status code indicates the strings are equal. A nonzero status code can be further positive or negative, indicating the compared string is longer or shorter than the specified string, respectively. This is demonstrated below:

Download  Run Code

Output:

Both strings are equal

2. Using operator==

A simple solution to determine whether two strings are equal or not is using the == relational operator, which uses the string::compare for the comparison. Following is a simple example demonstrating its usage:

Download  Run Code

Output:

Both strings are equal

That’s all about comparing two strings in C++.