将字符串中指定部分进行反转 比如将"abcdef" 翻转成 “aedcbf”
package com.hspedu.exercise;
//将字符串中指定部分进行反转 比如将"abcdef" 反转成 "aedcbf"
public class StringReverseT {
public static void main(String[] args) {
String str = "abcdef";
//翻转前字符串
System.out.println(str);
//异常处理,报错后直接return;
try {
str = reverse(str, 1, 4);
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
//翻转后字符串
System.out.println(str);
}
public static String reverse(String str, int start, int end) {
//对正确条件进行取反操作
if (!(str != null && start >= 0 && end > start && end < str.length())) {
//满足取反后的条件直接new一个运行时异常返回
throw new RuntimeException("参数不正确");
}
//String字符串转换char数组
char[] chars = str.toCharArray();
char temp = ' '; //交换辅助变量
for (int i = start, j = end; i < j; i++, j--) {
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
//使用chars重新构建一个String返回
return new String(chars);
}
}



