交换字符串位置
package homework;
public class Change {
public static void main(String[] args) {
String str = "abcdef";
System.out.println("==交换前==");
System.out.println(str);
try {
str = reverse(str, 1, 5);
System.out.println("输入无误");
} catch (Exception e){
System.out.println(e.getMessage());
return;
}
System.out.println("==交换后==");
System.out.println(str);
}
public static String reverse( String str ,int start, int end){
//对输入的参数做一个验证
//对所有正确的情况取反
if ( !(str != null && start >= 0 && end >start && end < str.length())){
throw new RuntimeException("输入的参数不正确");
}
char[] chars = str.toCharArray();
for (int i = start ,j = end ; i < j; i++ , j--) {
char temp = chars[i];
chars[i] = chars[j];
chars [j] = temp ;
}
return new String(chars);
}
}
运行结果如下