Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting characters within a string

String newStr;

public RandomCuriosity(String input){
    newStr = input;
}

public void shiftChars(){
    char[] oldChar = newStr.toCharArray();
    char[] newChar = new char[oldChar.length];
    newChar[0] = oldChar[oldChar.length-1];
    for(int i = 1; i < oldChar.length; i++){
        newChar[i] = oldChar[i-1];
    }
    newStr = String.valueOf(newChar);
}

I created a method that shifts characters forward by one. For example, the input could be:

The input: Stackoverflow

The output: wStackoverflo

How I did it is I mutated an instance of a string. Convert that string to a char array (calling it oldChar), assigned the last index of of oldChar as the first index of newChar, and made a for-loop that took the first index of oldChar as the second index of my new Char array and so forth. Lastly, I converted the char array back to a string.

I feel like I did way too much to do something very simple. Is there a more efficient way to do something like this?

EDIT Thanks for the great answers!

like image 690
theGreenCabbage Avatar asked Nov 27 '13 20:11

theGreenCabbage


1 Answers

newStr = newStr.charAt(newStr.length() - 1) + newStr.substring(0, newStr.length() - 1);
like image 74
JB Nizet Avatar answered Oct 09 '22 17:10

JB Nizet