1.Reverse string using loop
- Reverse string using iterator
-
Check whether string is palindrome or not
Below is my project explorer setup:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package stringOperation; public class StringOperation { // Reverse String using Iteration public String reverString(String str){ StringBuilder reverseString = new StringBuilder(); int i = str.length(); while(i>0){ i--; reverseString.append(str.charAt(i)); } return reverseString.toString(); } // Reverse String using Recursion public String reverseStringWithRecursion(String str) { //last element of string if (str.length() == 1) { return str; } return reverseStringWithRecursion(str.substring(1)) + str.charAt(0); } //Check whether given String is palindrom or not public boolean checkPalindrome(String str){ int j = str.length(); boolean flag = true; for(int i=0;i<j/2;i++){ if(str.charAt(i) == str.charAt(j-1-i)){ continue; }else{ flag = false; break; } } return flag; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import stringOperation.StringOperation; public class MainPractise { public static void main(String[] args) { String str = "I want you to reverse me"; StringOperation so = new StringOperation(); System.out.println("With Loop :"+so.reverString(str)); System.out.println("With Recursion:"+so.reverseStringWithRecursion(str)); str = "Not PP toN"; System.out.println(so.checkPalindrome(str)); str = "I am not palindrome"; System.out.println(so.checkPalindrome(str));; } } |
Output:
1 2 3 4 |
With Loop :em esrever ot uoy tnaw I With Recursion:em esrever ot uoy tnaw I true false |
You can have above code from GIT.
https://github.com/Niravkumar-Patel/SnippetExampleRepo.git