0
0
C++programming~5 mins

Character vs string comparison in C++

Choose your learning style9 modes available
Introduction

We compare characters and strings to check if they are the same or different. Characters are single letters, while strings are groups of letters.

Checking if a typed letter matches a specific character, like 'y' or 'n'.
Comparing user input to a word, like checking if input is "yes" or "no".
Validating a single character in a password or code.
Deciding actions based on a single letter or a whole word.
Syntax
C++
char c = 'a';
std::string s = "a";

// Compare character to character
if (c == 'a') {
    // do something
}

// Compare string to string
if (s == "a") {
    // do something
}

// Comparing char to string directly is not allowed
// if (c == s) { // error }

// To compare char and string, convert char to string first
if (std::string(1, c) == s) {
    // do something
}

Characters use single quotes: 'a'. Strings use double quotes: "a".

You cannot compare a char and a string directly in C++ without conversion.

Examples
Compare a character variable to a character literal.
C++
char c = 'x';
if (c == 'x') {
    // true
}
Compare a string variable to a string literal.
C++
std::string s = "hello";
if (s == "hello") {
    // true
}
Convert char to string to compare with a string.
C++
char c = 'a';
std::string s = "a";
if (std::string(1, c) == s) {
    // true
}
Sample Program

This program shows how to compare a character to a character literal, a string to a string literal, and how to compare a character to a string by converting the character to a string first.

C++
#include <iostream>
#include <string>

int main() {
    char c = 'g';
    std::string s = "g";

    if (c == 'g') {
        std::cout << "Character matches 'g'\n";
    }

    if (s == "g") {
        std::cout << "String matches \"g\"" << std::endl;
    }

    // Direct comparison (char == string) is not allowed
    // So convert char to string first
    if (std::string(1, c) == s) {
        std::cout << "Char and string are equal after conversion" << std::endl;
    }

    return 0;
}
OutputSuccess
Important Notes

Remember to use single quotes for characters and double quotes for strings.

Trying to compare a char and a string directly will cause a compile error in C++.

Use std::string(1, c) to convert a char to a string of length 1.

Summary

Characters and strings are different types in C++.

You can compare characters to characters and strings to strings directly.

To compare a character with a string, convert the character to a string first.