Check if a Char Array is equal to a string in C++

This tutorial will discuss about unique ways to check if a char array is equal to a string.

Table Of Contents

Technique 1: Using strcmp()

The strcmp() function accepts two strings (char pointers) as arguments, and returns 0 if both the strings are equal. We can use this function to compare a char array and a std::string object.

We can fetch the char pointer, pointing to the internal data of string object using the string::c_str() function. Then we can pass this char pointer to strcmp() function, along with a char array. If char array is equal to the string pointed by char array, then the strcmp() will returns 0.

Let’s see the complete example,

#include <iostream>
#include <string>
#include <string.h>

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

    // Compare a Char Array with a String
    if(strcmp(arr, strValue.c_str()) == 0)
    {
        std::cout<<"Both Char Array and String are equal \n";
    }
    else
    {
        std::cout<<"Both Char Array and String are not equal \n";
    }

    return 0;
}

Output :

Both Char Array and String are equal

Technique 2: Using string::compare() function

As we want to compare a std::string object and a char array, so we can use the compare() function of string class. It accepts a char pointer as an argument, and compares it with the calling string object. If the characters in both the strings are equal, then it will return 0.

So, we can pass the char array into the compare() function of string class, to check if a char array is equal to a string or not.

Let’s see the complete example,

#include <iostream>
#include <string>

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

    // Compare a Char Array with a String
    if(strValue.compare(arr) == 0)
    {
        std::cout<<"The Char Array and String are equal \n";
    }
    else
    {
        std::cout<<"The Char Array and String are not equal \n";
    }

    return 0;
}

Output :

The Char Array and String are equal

Summary

Today we learned about several ways to check if a char array is equal to a string. 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