PHP | Program to check a string is a rotation of another string
Given the two strings we have to check if one string is a rotation of another string.
Examples:
Input : $string1 = "WayToCrack", $string2 = "CrackWayTo"; Output : Yes Input : $string1 = "WillPower" $string2 = "lliW"; Output : No.
The above problem can be easily solved in other languages by concatenating the two strings and then would check if the resultant concatenated string contains the string or not. But in PHP we will use an inbuilt function to solve the problem. The inbuilt functions used are:
- strpos(): The function generally accepts the two parameters first one to specify the string to be searched and the other one to find in the specified string.
In PHP solution strpos() will give the last position of string if found in the specified string.
Below is the implementation of above approach
<?php function rotation_string( $string1 , $string2 ) { // if both strings are not same length then stop if ( strlen ( $string1 ) != strlen ( $string2 )) echo "No" ; // concatenate $string1 to itsel, if both // strings are of same length if ( strlen ( $string1 ) == strlen ( $string2 )) $string1 = $string1 . $string1 ; if ( strpos ( $string1 , $string2 ) > 0) echo "Yes" ; else echo "No" ; } // Driver code $string1 = "WayToCrack" ; $string2 = "CrackWayTo" ; rotation_string( $string1 , $string2 ); ?> |
Yes
Recommended Posts:
- JavaScript | Check if a string is a valid JSON string
- How to check if URL contain certain string using PHP?
- PHP to check substring in a string
- JavaScript | Check if a variable is a string
- How to check if a string is html or not using JavaScript?
- How to check if string contains only digits in JavaScript ?
- How to check a string begins with some given characters/pattern ?
- How to check a string is entirely made up of the same substring in JavaScript ?
- JavaScript | Check if a string is a valid hex color representation
- How to check empty/undefined/null string in JavaScript?
- Program to generate random string in PHP
- JavaScript | Difference between String.slice and String.substring
- PHP program to find the length of the last word in string
- ES6 | String
- How to get parameters from a URL string in PHP?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.