w3resource

Java: Given a string and an offset, rotate string by offset

Java Basic: Exercise-114 with Solution

Rotate String by Offset

Write a Java program that rotates a string by an offset (rotate from left to right.

Pictorial Presentation:

Java Basic Exercises: Given a string and an offset, rotate string by offset

Sample Solution:

Java Code:

import java.util.*;

public class Example114 {
    public static void main(String[] arg) {
        // Input string
        String str = "abcdef";
        
        // Convert the string to a character array
        char[] A = str.toCharArray();
        
        // Define the offset for rotation
        int offset = 3;
        
        // Calculate the length of the character array
        int len = A.length;
        
        // Ensure that the offset is within the bounds of the array
        offset %= len;
        
        // Reverse the first portion of the array
        reverse(A, 0, len - offset - 1);
        
        // Reverse the second portion of the array
        reverse(A, len - offset, len - 1);
        
        // Reverse the entire array to complete the rotation
        reverse(A, 0, len - 1);
        
        // Print the rotated array
        System.out.println("\n" + Arrays.toString(A));
    }

    // Helper function to reverse a portion of a character array
    private static void reverse(char[] str, int start, int end) {
        while (start < end) {
            char temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
        }
    }
}

Sample Output:

[d, e, f, a, b, c]   

Flowchart:

Flowchart: Java exercises: Given a string and an offset, rotate string by offset

Java Code Editor:

Previous: Write a Java program to merge two given sorted array of integers and create a new sorted array.
Next: Write a Java program to check if a positive number is a palindrome or not.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/basic/java-basic-exercise-114.php