how to check char array equality in c++
To check the equality of two char arrays in C++, you can use the strcmp()
function from the <cstring>
library. Here are the steps to do so:
- Include the
<cstring>
library at the beginning of your code:
#include <cstring>
- Declare two char arrays that you want to compare:
char array1[] = "Hello";
char array2[] = "World";
- Use the
strcmp()
function to compare the two arrays:
int result = strcmp(array1, array2);
- Check the value of
result
to determine the equality of the arrays. Thestrcmp()
function returns: - 0 if the arrays are equal
- a negative value if
array1
is lexicographically less thanarray2
- a positive value if
array1
is lexicographically greater thanarray2
Here is an example that demonstrates these steps:
#include <iostream>
#include <cstring>
int main() {
char array1[] = "Hello";
char array2[] = "World";
int result = strcmp(array1, array2);
if (result == 0) {
std::cout << "The arrays are equal." << std::endl;
} else if (result < 0) {
std::cout << "array1 is less than array2." << std::endl;
} else {
std::cout << "array1 is greater than array2." << std::endl;
}
return 0;
}
The output of this example will be "array1 is less than array2." because the ASCII value of 'H' (first character of array1
) is less than the ASCII value of 'W' (first character of array2
).
I hope this explanation helps! Let me know if you have any further questions.