Interchange character in String

Dipendra Pokharel :

I have a string.

String word = "Football";

I need to place the first character of the string to the very end of the string. Here is my solution.

public class charToString{
    public static void main(String[] args){
        String testString = "Football";
        char[] stringToCharArray = testString.toCharArray();

        for(int i=0;i<(stringToCharArray.length-1);i++){
            char temp = stringToCharArray[i];
            stringToCharArray[i]= stringToCharArray[i+1];
            stringToCharArray[i+1] = temp;

        }//end of for

        String resulT = new String(stringToCharArray); //result with desired output
        System.out.println(resulT);
    }// end of main
}

Is this an efficient way to complete my task? Or can you suggest me a more efficient way to do this?

Andy Turner :

A more efficient solution than substring and concatenation would be to use a StringBuilder:

String result =
    new StringBuilder(word.length())
        .append(word, 1, word.length())
        .append(word, 0, 1) // or .append(word.charAt(0))
        .toString();

This simply avoids creating the substrings from word.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114652&siteId=1