Move characters in a text string with a specified number of positions
I am new to programming and I am trying to write a program that moves characters in a text string with a specified number of positions.
The program must include a method, the input of which will be a text string (type String) and number of positions (type int
). The result will be a string with displaced characters.
For example, moving 4 positions:
rabb it eats a carrot it eats a carrot rabb
I now have this partial code. I can erase the first characters, but I don't know how to put them at the end of this text. How can i do this?
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
char firstLetter = a.charAt(0);
b--;
a = a.substring(b);
String m = a + firstLetter ;
System.out.println("now it is "+ m);
}
source to share
import java.util.*; public class JavaApplication5 { public static void main(String[] args) { System.out.println("enter the text: "); Scanner cti = new Scanner(System.in); String a = cti.nextLine(); System.out.println("enter number of positions= "); int b = cti.nextInt(); String firstPart = a.substring(0,b); // line 1 b--; a = a.substring(b); String m = a + firstPart ; // line 2 System.out.println("now it is "+ m); } }
See the changes above in the statement marked with comment line 1 and line 2.
On line 1 we get the first part of the line and on line 2 we add at the end of the second part of the line.
source to share
Better to use the modulus operator to calculate the number of shifts. When the initial shift number is greater than the length of the string. Check it:
public String shift(String string,int n){
int nshift = string.length() < n ? n%string.length() : n ;
String a = string.substring(0,nshift);
return string.substring(nshift) + a ;
}
source to share
Another version. All work is mostly done in 1 line:
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
Anyway, the complete code is:
import java.util.*;
public class ShiftLetters {
public static void main(String[] args) {
System.out.print("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.print("Enter number of positions: ");
int b = cti.nextInt();
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
System.out.println(result);
}
}
Also, you can be more precise with your indentation style to improve readability.
source to share