To check to see if the string is a rotation of the original – Java

A program to check if a word is a rotation of another. If it is a rotation it will return true however if it is not it will return false.


public class RotationOf
{
    public static boolean isSubstring(String big, String small)
    {
        if (big.indexOf(small) >= 0)
        {
            return true;
        }//if

        else
        {
            return false;
        }//else
    }

    public static boolean isRotation(String s1, String s2)
    {
        int len = s1.length();

            /* check that s1 and s2 are equal length and not empty */
        if (len == s2.length() && len > 0)
        {
            /* concatenate s1 and s1 within new buffer */
            String s1s1 = s1 + s1;
            return isSubstring(s1s1, s2);
        }//if
        return false;
    }//rotation

    public static void main(String[] args)
    {
        String[][] pairs = {{"apple", "pleap"}, {"waterbottle", "erbottlewat"}, {"camera", "macera"}};
        for (String[] pair : pairs)
        {
            String word1 = pair[0];
            String word2 = pair[1];
            boolean is_rotation = isRotation(word1, word2);
            System.out.println(word1 + ", " + word2 + ": " + is_rotation);
        }//for
    }//main
}//class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s