String Operations

1.Reverse string using loop

2. Reverse string using iterator

3. Check whether string is palindrome or not

 

Below is my project explorer setup:

StringOperationProjectExplorer


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;
	}	
	
}

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:

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.

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git


Leave a Reply

Your email address will not be published. Required fields are marked *