java - 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?
解决方案
您使用子字符串的解决方案很好,但这是使用正则表达式的替代解决方案:
String word = "Football";
String result = word.replaceAll("^(.)(.*)$", "$2$1");
System.out.println(result);
推荐阅读
- java - 从 JSON 中获取值(映射
) 与 JSONObject - android - 如何在 Retrofit Kotlin 中成功响应后清除 LiveData 对象的数据
- python - 当我有一个开始和结束的熊猫数据框时,需要弄清楚重叠
- javascript - Github - 读取边带数据包时意外断开连接
- python - Python Selenium:登录自动化,层问题?
- android-fragments - 在viewpager中将数据发送到一个片段到另一个片段
- ios - 对于 UIView 子类,如果我们使用 CGRect 参数覆盖初始化程序,为什么会自动提供带有空参数的初始化程序?
- sql - 根据规则对数据集进行分组?
- mysql - 如何检查数据库字段是否包含非中断空间?
- android - 与 ViewPager2 一起使用时出现 PorterDuffXfermode 错误