Display String in Circular Format in Java


 

Display String in Circular Format in Java

In this section, you will learn how to display string in a circular format.

In this section, you will learn how to display string in a circular format.

Display String in Circular Format in Java

In this section, you will learn how to display string in a circular format.For this, we have specified the string 'WORD'. Now we have to shift each character of the string in the circular format. So we have created following method that will shift each character to left in a circular way:

public static void shiftLeft(String[] array, int amount) {
		for (int j = 0; j < amount; j++) {
			String a = array[0];
			int i;
			for (i = 0; i < array.length - 1; i++)
				array[i] = array[i + 1];
			array[i] = a;
		}
	}

Here is the code:

public class CircularFormat {
	public static void shiftLeft(String[] array, int amount) {
		for (int j = 0; j < amount; j++) {
			String a = array[0];
			int i;
			for (i = 0; i < array.length - 1; i++)
				array[i] = array[i + 1];
			array[i] = a;
		}
	}

	public static void printArray(String[] array) {
		for (int x = 0; x < array.length; x++) {
			System.out.print(array[x]);
		}
	}

	public static void main(String[] args) {
		String st = "WORD";
		String array[] = st.split("");
		int len = array.length;
		shiftLeft(array, 2);
		printArray(array);
		System.out.println(" ");
		shiftLeft(array, 2);
		printArray(array);
		System.out.println(" ");
		shiftLeft(array, 2);
		printArray(array);
		System.out.println(" ");
		shiftLeft(array, 2);
		printArray(array);
	}
}

Output:

ORDW
DWOR
WORD
RDWO

Ads