首页 > 解决方案 > Interchange character in String

问题描述

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?

标签: javastringcharacter

解决方案


您使用子字符串的解决方案很好,但这是使用正则表达式的替代解决方案:

String word = "Football";
String result = word.replaceAll("^(.)(.*)$", "$2$1");
System.out.println(result);

推荐阅读