Shifting Characters Within a String

Shifting characters within a string

newStr = newStr.charAt(newStr.length() - 1) + newStr.substring(0, newStr.length() - 1);

Shifting characters in a string to the left

What you want is to split the string at position k and merge both parts together again but in reverse order.
The main problem is that k may be greater than or equal to the size of your string. So you need to bring k into a valid range again.

public static String cyclicLeftShift(String s, int k){
k = k%s.length();
return s.substring(k) + s.substring(0, k);
}

Testing the method:

public static void main(String[] args)
{
String test = "Hello World";
for(int i = 0; i < test.length()*3; i++)
System.out.println(cyclicLeftShift(test, i));
}

Output:

Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
WorldHello
WorldHello
orldHello W
rldHello Wo
ldHello Wor
dHello Worl
Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
WorldHello
WorldHello
orldHello W
rldHello Wo
ldHello Wor
dHello Worl
Hello World
ello WorldH
llo WorldHe
lo WorldHel
o WorldHell
WorldHello
WorldHello
orldHello W
rldHello Wo
ldHello Wor
dHello Worl

Shifting the characters in a string in Java

I solved it
Problem

Read a word from the user and display the string with the letters shifted to the right by two positions and with the letters shifted to the left by two positions in the string. Save all of the three strings in separate variables and display all three of them at the end of the program.

import java.util.Scanner;   
public class StringShiftTwoLeftThenRight
{
public static void main(String[] args)
{
String word, rightShift = "", leftShift = "";

Scanner keyboard = new Scanner(System.in);
System.out.print("\nEnter a word: ");
word = keyboard.nextLine();
rightShift = (word.substring((0),
(word.length()-2)));

leftShift = (word.substring((2),(word.length())));

System.out.println("\nThe String shifted two to right looks like this: " + rightShift);
System.out.println("\nThe String shifted two to left looks like this: " + leftShift);
System.out.println("\nThe String as it is looks like: " + word);
}
}


Related Topics



Leave a reply



Submit