- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
A Program to check if strings are rotations of each other or not?
Here we will see one program that can tell whether two strings are rotation of each other or not. The rotation of strings is like −
Suppose two strings are S1 = ‘HELLO’, and S2 = ‘LOHEL’ So they are rotation of each other. By rotating HELLO three position to the left it will be LOHEL.
To solve this problem, we will concatenate the first string with itself, then check whether the second one is present in the concatenated string or not. So for HELLO, it will be HELLOHELLO. Then this concatenated string contains the LOHEL. [HELLOHELLO].
Algorithm
isRotation(str1, str2)
begin if lengths of str1, and str2 are not same then return false; temp := concatenate str1 with str1 itself if temp contains str2, then return true otherwise return false end
Example
#include<iostream> using namespace std; bool isRotation(string str1, string str2){ if(str1.length() != str2.length()) return false; string con_str = str1 + str1; if(con_str.find(str2) != string::npos){ return true; } else { return false; } } main() { string str1, str2; cout << "Enter two strings: "; cin >> str1 >> str2; if(isRotation(str1, str2)){ cout << "Two strings are rotation of each other"; } else { cout << "Two strings are not rotation of each other"; } }
Output
Enter two strings: STACK CKSTA Two strings are rotation of each other
- Related Articles
- Check if strings are rotations of each other or not in Python
- Write a program in JavaScript to check if two strings are anagrams of each other or not
- Program to check strings are rotation of each other or not in Python
- Check if all rows of a matrix are circular rotations of each other in Python
- C Program to check if two strings are same or not
- Check if two strings are anagram of each other using C++
- How to check if two Strings are anagrams of each other using C#?
- Check if two strings are equal or not in Arduino
- Java Program to check whether two Strings are an anagram or not.
- Check if bits in range L to R of two numbers are complement of each other or not in Python
- Check whether two strings are anagram of each other in Python
- Program to check whether final string can be formed using other two strings or not in Python
- Program to check two strings are 0 or 1 edit distance away or not in Python
- C++ Program to check if given numbers are coprime or not
- Check if concatenation of two strings is balanced or not in Python

Advertisements