Compare Two Strings in C++


Q. Write a C++ program to compare two strings.

#include <iostream>   
#include <cstring>
using namespace std;

int main () {
    char str1[30] = "Onlinetpoint";
    char str2[30] = "Onlinetpoint";
	if(strcmp(str1,str2)==0)
	{
	    cout << "str1 & str2 both strings are equal";
	}
	else
	{
	    cout << "str1 & str2 both strings are not equal";
	}
    return 0;
}

Q. Write an algorithm to compare two strings.

1. Start
2. Initialize the first string `str1` with the value `"Onlinetpoint"`.
3. Initialize the second string `str2` with the value `"Onlinetpoint"`.
4. Use the `strcmp` function from `` library to compare `str1` and `str2`.
    - `strcmp(str1, str2)` returns:
    - `0` if both strings are equal,
    - A negative value if `str1` is lexicographically less than `str2`,
    - A positive value if `str1` is lexicographically greater than `str2`.
5. If `strcmp(str1, str2) == 0` (strings are equal):
    - Print: `"str1 & str2 both strings are equal"`.
6. Else (strings are not equal):
    - Print: `"str1 & str2 both strings are not equal"`.
7. End 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.