Check for string rotation

Check if string s2 is a rotation of string s1. Example: "efulhop" is a rotation of "hopeful"
/*
 * RotationCheck.cpp
 *
 *  Created on: Apr 13, 2012
 *      Author: Kiran Hegde
 */

#include <iostream>
#include <string>
#include <vector>

using namespace std;

/**
 * Return true if s1 and s2 are just rotations of each other
 */
bool checkIfRotation(string s1, string s2) {
    if (s1.length() != s2.length())
        return false;
    string s1s1 = s1.append(s1);
    if (s1s1.find(s2) != string::npos)
        return true;
    return false;
}

/**
 * Test the function
 */
int main() {
    string s1 = "chariot";
    string s2 = "riotcha";
    cout << s2 << (checkIfRotation(s1, s2)? " IS ": " IS NOT ") \
            << " rotation of " << s1 << endl;

    s1 = "nowhere";
    s2 = "onwhere";
    cout << s2 << (checkIfRotation(s1, s2)? " IS ": " IS NOT ") \
                << " rotation of " << s1 << endl;

    return 0;
}
Comments