如有错误,请指出
public class StringReverse {
public static void main(String[] args) {
String str = "abcdefghijk";
// char s = str.charAt(0);
// System.out.println(s);
System.out.println(str);
//try-catch快捷键CTRL+alt+t
try {
reverse(str, 1, 72);
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
}
/*
思路分析
(1)先把方法确定
(2)可以把String转成char[]数组, 因为char[],的元素可以交换
*/
public static String reverse(String str, int start, int end){
// //对输入的数字做一个防护机制
//缺点,有想不到的错误情况,会漏掉某些错误情况
// if (end >= str.length() || start < 0){
// System.out.println("您输入的范围有误");
// System.exit(0);
// }
//老师技巧
//(1)写出正确的情况
//(2)然后取反即可
if (!(str != null && end > start && start >= 0 && end < str.length())){
System.out.println("您输入的范围有误");
throw new RuntimeException("输入异常");
}
//方法代码
char temp = ' ';
char[] replaces = new char[str.length()];
char[] chars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {//将String保存到char[]数组中
chars[i] = str.charAt(i);
replaces[i] = str.charAt(i);
}
//[a, b, c, d, e, f]
for (int i = start, j = end; i <= end; i++, j--) {//交换字符
temp = chars[i];
chars[i] = replaces[j];
replaces[j] = temp;
}
//清空字符串String
str = "";
for (int i = 0; i < chars.length; i++) {
str += chars[i];
}
System.out.println(str);
System.out.println(Arrays.toString(replaces));
System.out.println(Arrays.toString(chars));
System.out.println("======");
return str;
}
}