Write a program to print reverse of a String using iteration?

 

Write a program to print reverse of a 
String using iteration?

import java.util.Scanner;
public class ReverseString {

    public static String reverse(String s) {
        char[] charArray = s.toCharArray();
        int start = 0;
        int end = charArray.length - 1;

        while (start < end) {
   // Swap characters at start and end indices
            char temp = charArray[start];
            charArray[start] = charArray[end];
            charArray[end] = temp;

      // Move indices towards the center
            start++;
            end--;
        }

//Convert the character array back to a String
        return new String(charArray);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String inputString = sc.nextLine();

    String reversedString = reverse(inputString);
System.out.println("Reversed string: " + reversedString);
    }
}

OUTPUT:-
PS C:\Users\Tausif\Desktop\Java> javac ReverseString.java PS C:\Users\Tausif\Desktop\Java> java ReverseString Enter a string: welcome Reversed string: emoclew PS C:\Users\Tausif\Desktop\Java>

Reverse of String using recursion

Tausif

Hi! My name is TAUSIF AHMAD I have completed B.Tech in Computer Science from Maulana Azad National Urdu University Hyderabad. I am always ready to have new experiences meet new people and learn new things. 1. I am very interested in Frontend Development. 2. I love video editing and graphics designing. 3. I enjoy challenges that enables to grow. 4. I am part time Blogger.

Post a Comment (0)
Previous Post Next Post