C++ String Comparing

Introduction

A string can be compared to string literals and other strings using the equality == operator.

Comparing a string to a string literal:

#include <iostream> 
#include <string> 

int main() /*from   w  w  w  . j av  a  2 s . c o m*/
{ 
    std::string s1 = "Hello"; 
    if (s1 == "Hello") 
    { 
        std::cout << "The string is equal to \"Hello\""; 
    } 
} 

Comparing a string to another string is done using the equality operator ==:

#include <iostream> 
#include <string> 

int main() //from  ww w. j av  a  2  s .c  om
{ 
    std::string s1 = "Hello"; 
    std::string s2 = "World."; 
    if (s1 == s2) 
    { 
        std::cout << "The strings are equal."; 
    } 
    else 
    { 
        std::cout << "The strings are not equal."; 
    } 
} 



PreviousNext

Related