猿问

交换字符串中的字符

我有一个字符串。


String word = "Football";

我需要将字符串的第一个字符放在字符串的末尾。这是我的解决方案。


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

}

这是完成任务的有效方法吗?或者你能建议我一个更有效的方法来做到这一点吗?


FFIVE
浏览 131回答 3
3回答

德玛西亚99

您使用子字符串的解决方案很好,但这是使用正则表达式的替代解决方案:String word = "Football";String result = word.replaceAll("^(.)(.*)$", "$2$1");System.out.println(result);

幕布斯7119047

您可以使用子字符串:testString.substring(1)&nbsp;+&nbsp;testString.substring(0,&nbsp;1)

千万里不及你

比子字符串和串联更有效的解决方案是使用 a StringBuilder:String result =&nbsp; &nbsp; new StringBuilder(word.length())&nbsp; &nbsp; &nbsp; &nbsp; .append(word, 1, word.length())&nbsp; &nbsp; &nbsp; &nbsp; .append(word, 0, 1) // or .append(word.charAt(0))&nbsp; &nbsp; &nbsp; &nbsp; .toString();这只是避免从word.
随时随地看视频慕课网APP

相关分类

Java
我要回答