I need help for another one of my assignments for CS Class.

On the rubric, one of the part said:

all characters are shifted right by two positions and the last two characters becomes the first two characters

The condition is that the string has to be entered by the user.

So, for example, if the user enters the string " Beginning",
I have to do this :
Beginning -> Beginni ng
-> gnBeginni

I partially understand this and I manage to move the letter by doing this:

char firstchar = input.charAt(input.length());
char secondchar = input.charAt ((input.length())-1);

 System.out.print (firstchar);
 System.out.print (input);

Problem whith what I did is that it prints :


What I want to do is remove "ng" from gnBeggining

How should I do that?

Thanks in advance.

4 Years
Discussion Span
Last Post by shifat96

If can use StringBuffer because its mutable

StringBuffer sb = new StringBuffer("begining");
        System.out.print(sb.insert(0, sb.subSequence(sb.length()-2, sb.length())).delete(sb.length()-2, sb.length()));

Please don't throw code like that at someone who is trying to learn. At the very least explain it properly. Even better explain enough for the OP to write it himself. That's the best way to learn.


@JamesCherrill , Sorry I will avoid this and try to give more explanation ,
StringBuffer is mutable sequence of characters, the length and content of the sequence can be changed through certain method calls,

sb.insert(int offset , String s)
This method returns the StringBuilder object and updates the value of the StringBuilder object which invoke the method call.

** sb.subSequence(int beginIndex,int endIndex)**
this one is method of String class, this returns character squnce

sb.delete(int start ,int end)
here substring removed from the original object

As of my experience this will give best solution what u expected .

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.