Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving the characters in a text string a specified number of positions

Tags:

java

string

I am new in programming and I am trying to write a program that moves the characters in a text string a specified number of positions.

The program must include a method whose inputs will be a text string (type String) and the number of positions (type int). The output will be a string with characters shifted.

For example, moving 4 positions:

rabbit eats a carrot
it eats a carrotrabb

Now I have this partial code. I can erase first characters but I don't know how to put them to the end of this text. How can i make it?

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);
}
like image 625
andrey shirokij Avatar asked Sep 15 '25 16:09

andrey shirokij


2 Answers

If you use regex, it's just one line:

return str.replaceAll("^(.{" + n + "})(.*)", "$2$1");
like image 66
Bohemian Avatar answered Sep 17 '25 08:09

Bohemian


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 statement marked with comment line 1 and line 2.

In line 1, we are getting the first part of string and in line 2, adding at the end of second string part.

like image 39
bsoren Avatar answered Sep 17 '25 08:09

bsoren