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
403 Forbidden When I Try to Post to My Spring API
Intellij Incorrectly Saying No Beans of Type Found for Autowired Repository
String Match of Only 3 Specific Words
Java Coding Converted to Pseudo Code
Java.Lang.Illegalargumentexception: Not a Managed Type: Class
Gradle: How to Exclude a Particular Package from a Jar
Java:Using Apache Poi How to Convert Ms Word File to Pdf
Java 8: How to Write Lambda Stream to Work With Jsonarray
Iterating Over Two Arrays Simultaneously Using for Each Loop in Java
Is There a Java Setting for Disabling Certificate Validation
Check If a Given Time Lies Between Two Times Regardless of Date
How to Set Environment Variable or System Property in Spring Tests
Could Not Extract Resultset in Hibernate
Spring Data JPA and Parameters That Can Be Null
How to Put a Scanner Input into an Array... for Example a Couple of Numbers