public class HomeWork01 {
public static void main(String[] args) {
String str = "12345678";
// 17654328
try {
System.out.println(reverse(str, 1, 6));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
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();
char temp = ' ';
for (int i = start, j = end; i < j; i++, j--) {
temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
return new String(chars);
}
public static String reverse3(String str) {
char[] chars = str.toCharArray();
char temp = ' ';
for (int i = 0; i < chars.length / 2; i++) {
temp = chars[i];
chars[i] = chars[chars.length - 1 - i];
chars[chars.length - 1 - i] = temp;
}
return new String(chars);
}
}
java 字符反转练习 带错误处理
最新推荐文章于 2024-07-16 22:23:56 发布