rotation of string in java
- An easy solution to verify rotation of strings is find occurences of String1 in String2.
- By using concat and contains we can verify rotation of given strings.
Program for rotation of strings using contains:
public class StringRotation {
public static void main(String[] args) {
String str1 = "ABCD";
String str2 = "CDAB";
if (str1.length() == str2.length() && (str1 + str1).contains(str2)) {
System.out.println("given strings are rotation");
} else {
System.out.println("given strings are not rotation");
}
}
}
Output:
|
rotation of string in java |
Program for rotation of strings using indexOf():
public class StringRotation {
public static void main(String[] args) {
String str1 = "ABAD";
String str2 = "ADAB";
if (str1.length() == str2.length() && (str1 + str1).indexOf(str2)!=-1) {
System.out.println("given strings are rotation");
} else {
System.out.println("given strings are not rotation");
}
}
}
Output:
|
rotation of string in java |
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.