How to check if a string is rotation of another string in Java

2 Answers

0 votes
public class MyClass {
    static boolean isRotation(String s1, String s2) { 
        return (s1.length() == s2.length()) &&  
               ((s1 + s1).contains(s2)); 
    } 
    public static void main(String args[]) {
        String s1 = "abbc"; 
        String s2 = "cabb"; 

        System.out.println((isRotation(s1, s2) == true) ? "yes" : "no");
      
        s1 = "abbc"; 
        s2 = "bbac"; 

        System.out.println((isRotation(s1, s2) == true) ? "yes" : "no");
    }
}



/*
run:

yes
no

*/

 



answered Sep 24, 2019 by avibootz
edited Sep 26, 2019 by avibootz
0 votes
public class MyClass {
    public static boolean checkRotatation(String s, String rotation) {
        if (s.length() != rotation.length()) {
          return false;
        }
 
        String concatenated = s + s;
        System.out.println(concatenated);
        if (concatenated.contains(rotation))  
            return true;  
 
        return false;
    }
    public static void main(String args[]) {
        String s="JavaVsC#";
        String rotation ="VsC#Java";
         
        if (checkRotatation(s, rotation)) {
            System.out.println("Yes");
        } else {
             System.out.println("No");
          }
    }
 
}
 
 
 
/*
run:
 
JavaVsC#JavaVsC#
Yes
 
*/

 



answered Jul 27, 2020 by avibootz

Related questions

1 answer 188 views
1 answer 194 views
1 answer 250 views
1 answer 215 views
1 answer 261 views
1 answer 237 views
...