Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
829 B
3
Indexable
import java.util.Scanner;

public class StringRearrangement {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String userInput = scanner.nextLine();
        String rearrangedString = rearrangeString(userInput);
        System.out.println("Rearranged string: " + rearrangedString);
    }

    public static String rearrangeString(String inputStr) {
        if (inputStr.length() % 2 != 0) {
            inputStr += " ";  // Adding a space at the end if the string length is odd
        }

        StringBuilder result = new StringBuilder();
        for (int i = 0; i < inputStr.length(); i += 2) {
            result.append(inputStr.charAt(i + 1)).append(inputStr.charAt(i));
        }

        return result.toString();
    }
}