Comparing two strings in C++
Last Updated :
23 Jun, 2022
Given two strings, how to check if the two strings are equal or not.
Examples:
Input : ABCD, XYZ
Output : ABCD is not equal to XYZ
XYZ is greater than ABCD
Input : Geeks, forGeeks
Output : Geeks is not equal to forGeeks
forGeeks is greater than Geeks
This problem can be solved using any of the following two methods
CPP
// CPP code to implement relational
// operators on string objects
#include <iostream>
using namespace std;
void relationalOperation(string s1, string s2)
{
if (s1 != s2)
{
cout << s1 << " is not equal to " << s2 << endl;
if (s1 > s2)
cout << s1 << " is greater than " << s2 << endl;
else
cout << s2 << " is greater than " << s1 << endl;
}
else
cout << s1 << " is equal to " << s2 << endl;
}
// Driver code
int main()
{
string s1("Geeks");
string s2("forGeeks");
relationalOperation(s1, s2);
string s3("Geeks");
string s4("Geeks");
relationalOperation(s3, s4);
return 0;
}
OutputGeeks is not equal to forGeeks
forGeeks is greater than Geeks
Geeks is equal to Geeks
Time Complexity: O(min(n,m)) where n and m are the length of the strings.
Auxiliary Space: O(max(n,m)) where n and m are the length of the strings.
This is because when string is passed in the function it creates a copy of itself in stack.
CPP
// CPP code perform relational
// operation using compare function
#include <iostream>
using namespace std;
void compareFunction(string s1, string s2)
{
// comparing both using inbuilt function
int x = s1.compare(s2);
if (x != 0) {
cout << s1
<< " is not equal to "
<< s2 << endl;
if (x > 0)
cout << s1
<< " is greater than "
<< s2 << endl;
else
cout << s2
<< " is greater than "
<< s1 << endl;
}
else
cout << s1 << " is equal to " << s2 << endl;
}
// Driver Code
int main()
{
string s1("Geeks");
string s2("forGeeks");
compareFunction(s1, s2);
string s3("Geeks");
string s4("Geeks");
compareFunction(s3, s4);
return 0;
}
OutputGeeks is not equal to forGeeks
forGeeks is greater than Geeks
Geeks is equal to Geeks
Time Complexity: O(min(n,m)) where n and m are the length of the strings.
Auxiliary Space: O(max(n,m)) where n and m are the length of the strings.
This is because when string is passed in the function it creates a copy of itself in stack.
Differences between C++ Relational operators and compare() :-
- compare() returns an int, while relational operators return boolean value i.e. either true or false.
- A single Relational operator is unique to a certain operation, while compare() can perform lots of different operations alone, based on the type of arguments passed.
- We can compare any substring at any position in a given string using compare(), which otherwise requires the long procedure of word-by-word extraction of string for comparison using relational operators.
Example:-
// Compare 3 characters from 3rd position
// (or index 2) of str1 with 3 characters
// from 4th position of str2.
if (str1.compare(2, 3, str2, 3, 3) == 0)
cout<<"Equal";
else
cout<<"Not equal";
- Using Relational operator
for (i = 2, j = 3; i <= 5 && j <= 6; i++, j++)
{
if (s1[i] != s2[j])
break;
}
if (i == 6 && j == 7)
cout << "Equal";
else
cout << "Not equal";
The above example clearly shows how compare() reduces lots of extra processing, therefore it is advisable to use it while performing substring comparison at some position, otherwise both perform almost in the same manner.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read