Compare a String and a char array in C++

This tutorial will discuss about unique ways to compare a string and a char array in C++.

Table Of Contents

Technique 1: Using string::compare() function

The string class in C++, provides a function compare(). It accepts another string or a character pointer, as an argument. It returns zero if the string passed as argument, and the calling string object are equal. It means if both the strings are equal, then it will return zero. So we can use it to compare a string and a char array. For that we just need to pass the char array as an argument on the compare() function. If it returns 0, then it means both the string and char pointer has smilar strings.

Let’s see the complete example,

#include <iostream>

int main()
{
    std::string strValue = "Tested";
    char arr[] = "Tested";

    // Compare a string and char array
    if (strValue.compare(arr) == 0)
    {
        std::cout<<"Both string & char array are equal \n";
    }
    else
    {
        std::cout<<"Both string & char array are not equal \n";
    }

    return 0;
}

Output :

Both string & char array are equal

Technique 2: Using strcmp() function

The cstring header file, provides a functions strcmp(). We can use it to compare two char pointers, and check if both contains the matching string or not. As we want to compare a string with a char array, so we can fetch the char pointer to nternal data from the std::string object, using the string::c_str() function. Then we can pass these two char pointers into the strcmp() function, and if t returns zero, then it means both the strings are equal.

Let’s see the complete example,

#include <iostream>
#include <cstring>

int main()
{
    std::string strValue = "Tested";
    char arr[] = "Tested";

    // compare a string and char array
    if (strcmp(strValue.c_str(), arr) == 0)
    {
        std::cout<<"Both string & char array are equal \n";
    }
    else
    {
        std::cout<<"Both string & char array are not equal \n";
    }

    return 0;
}

Output :

Both string & char array are equal

Summary

Today we learned about several ways to compare a string and a char array in C++. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top