
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Hello World
- C++ Omitting Namespace
- C++ Tokens
- C++ Constants/Literals
- C++ Keywords
- C++ Identifiers
- C++ Data Types
- C++ Numeric Data Types
- C++ Character Data Type
- C++ Boolean Data Type
- C++ Variable Types
- C++ Variable Scope
- C++ Multiple Variables
- C++ Basic Input/Output
- C++ Modifier Types
- C++ Storage Classes
- C++ Numbers
- C++ Enumeration
- C++ Enum Class
- C++ References
- C++ Date & Time
- C++ Operators
- C++ Arithmetic Operators
- C++ Relational Operators
- C++ Logical Operators
- C++ Bitwise Operators
- C++ Assignment Operators
- C++ sizeof Operator
- C++ Conditional Operator
- C++ Comma Operator
- C++ Member Operators
- C++ Casting Operators
- C++ Pointer Operators
- C++ Operators Precedence
- C++ Unary Operators
- C++ Control Statements
- C++ Decision Making
- C++ if Statement
- C++ if else Statement
- C++ Nested if Statements
- C++ switch Statement
- C++ Nested switch Statements
- C++ Loop Types
- C++ while Loop
- C++ for Loop
- C++ do while Loop
- C++ Foreach Loop
- C++ Nested Loops
- C++ break Statement
- C++ continue Statement
- C++ goto Statement
- C++ Strings
- C++ Strings
- C++ Loop Through a String
- C++ String Length
- C++ String Concatenation
- C++ String Comparison
- C++ Functions
- C++ Functions
- C++ Multiple Function Parameters
- C++ Recursive Function
- C++ Return Values
- C++ Function Overloading
- C++ Function Overriding
- C++ Default Arguments
- C++ Arrays
- C++ Arrays
- C++ Multidimensional Arrays
- C++ Pointer to an Array
- C++ Passing Arrays to Functions
- C++ Return Array from Functions
- C++ Structure & Union
- C++ Structures
- C++ Unions
- C++ Pointers
- C++ Pointers
- C++ Dereferencing
- C++ Modify Pointers
- C++ Class and Objects
- C++ Object Oriented
- C++ Classes & Objects
- C++ Class Member Functions
- C++ Class Access Modifiers
- C++ Static Class Members
- C++ Static Data Members
- C++ Static Member Function
- C++ Inline Functions
- C++ this Pointer
- C++ Friend Functions
- C++ Pointer to Classes
- C++ Constructors
- C++ Constructor & Destructor
- C++ Default Constructors
- C++ Parameterized Constructors
- C++ Copy Constructor
- C++ Constructor Overloading
- C++ Constructor with Default Arguments
- C++ Delegating Constructors
- C++ Constructor Initialization List
- C++ Dynamic Initialization Using Constructors
- C++ Inheritance
- C++ Inheritance
- C++ Multiple Inheritance
- C++ Multilevel Inheritance
- C++ Object-oriented
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
- C++ Virtual Function
- C++ Pure Virtual Functions & Abstract Classes
- C++ File Handling
- C++ Files and Streams
- C++ Reading From File
- C++ Advanced
- C++ Exception Handling
- C++ Dynamic Memory
- C++ Namespaces
- C++ Templates
- C++ Preprocessor
- C++ Signal Handling
- C++ Multithreading
- C++ Web Programming
- C++ Socket Programming
- C++ Concurrency
- C++ Advanced Concepts
- C++ Lambda Expression
- C++ unordered_multiset
C++ String Comparison
C++ string comparison refers to the process of evaluating two strings to determine their equality or their order based on lexicographical rules.
String comparison can be done by using built-in operators such as ==, !=, <, and > or by the compare() method. But by default these comparisons are case-sensitive, which means "tutorial point" and "Tutorial point" are considered different. String comparison plays an important role in performing tasks like sorting, searching, and input validation.
Types of String in C++
Basically there are two primary types of string in C++ −
- C-style strings − This string in C++ is an array of characters with a null character ('\0').
- std::string − This string is a part of the C++ Standard Library which provides a more robust and user-friendly way to handle strings because it manages memory automatically, allows dynamic resizing, and provides a vast set of member functions for manipulation like concatenation, substring extraction, and searching.
Comparing C-Style Strings
Here's how you can compare C-style strings −
1. strcmp()
You can use the strcmp() function from the <cstring> library to compare two strings.
Example
Heres a given example showing a comparison between two C-style strings −
#include <iostream> #include <cstring> int main() { const char* str1 = "hello"; const char* str2 = "Tutorialspoint Learner"; int result = strcmp(str1, str2); if (result < 0) { std::cout << "str1 is less than str2\n"; } else if (result > 0) { std::cout << "str1 is greater than str2\n"; } else { std::cout << "str1 is equal to str2\n"; } return 0; }
Output
str1 is greater than str2
Explanation
- The strcmp function compares the two strings and returns negative (str1 < str2), zero(str1 = str2) and positive(str1 > str2).
- In this case, "hello" is lexicographically greater than "Tutorialspoint Learner", so the output is "str1 is greater than str2".
- In lexicographical order, strings are compared character by character based on their ASCII values, where 'h' (ASCII 104) and 'T' (ASCII 84)
- So 104 > 84 then this comparison resulted in "hello" being greater than "Tutorialspoint Learner".
2. strcoll()
The strcoll() function compares two C-strings according to the current locale, which is useful for internationalization. It behaves similarly to strcmp() but takes into account locale-specific rules.
Example
#include <iostream> #include <cstring> #include <locale> int main() { const char* str1 = "hello"; const char* str2 = "Tutorialspoint Learner"; // Set the locale (optional, depends on your environment) std::setlocale(LC_COLLATE, "en_US.UTF-8"); int result = strcoll(str1, str2); if (result < 0) { std::cout << "str1 is less than str2\n"; } else if (result > 0) { std::cout << "str1 is greater than str2\n"; } else { std::cout << "str1 is equal to str2\n"; } return 0; }
Output
str1 is greater than str2
Explanation
- The std::setlocale() function sets the locale for string collation (comparison) to "en_US.UTF-8", which is the U.S. English locale.
- The strcoll() function compares str1 and str2 according to the current locale.
- It returns a "-ve" value if str1 < str2, 0 if they are equal, and a "+ve" value if str1 > str2.
- Since 'h' (ASCII 104) > 'T' (ASCII 84) therefor output is 'h' is greater than 'T'.
Comparing std::string
In C++ for comparing std::string objects have various methods that give different ways of accessing their equality or relative order.
1. Comparison Operators
Comparison operators give access to compare two std::string objects directly.
This comparison is also done lexicographically which means characters are compared based on their ASCII values. These are the following −
- == (Equality)
- != (Inequality)
- < (Less than)
- > (Greater than)
- <= (Less than or equal to)
- >= (Greater than or equal to)
Example
#include <iostream> #include <string> int main() { std::string str1 = "Allen"; std::string str2 = "allen"; std::cout << (str1 == str2) << std::endl; // false (0) std::cout << (str1 != str2) << std::endl; // true (1) std::cout << (str1 < str2) << std::endl; // true (1) std::cout << (str1 > str2) << std::endl; // false (0) return 0; }
Output
0 1 1 0
Explanation
Since the ASCII value of A (65) is less than a (97), So receiving output accordingly.
2. std::string::compare() Method
The std::string::compare() method is also used to compare the value of two strings. It returns an integer value based on the lexicographical comparison.
- 0: if both strings are equal
- > 0 (+ve) : if the first string is greater
- < 0 (-ve) : if the first string is lesser
Example
#include <iostream> #include <string> int main() { std::string str1 = "apple"; std::string str2 = "banana"; std::cout << str1.compare(str2) << std::endl; std::cout << str1.compare("apple") << std::endl; return 0; }
Output
-1 0
Explanation
- At first, since 'a' (ASCII 97) is less than 'b' (ASCII 98) so output is a negative number (-1).
- In the second, the output is 0 as values stored in str1 and "apple" are the same.