简单的将字符串中的一段字符进行交换
- package com.hspedu.HomeworkRverse;
-
- import com.sun.org.apache.bcel.internal.generic.ATHROW;
-
- /**
- * @author: guorui fu
- * @versiion: 1.0
- */
- public class RverseExercise {
- public static void main(String[] args) {
- String str = "abcdef";
- System.out.println("交换前====");
- System.out.println(str);
- try {
- str = reverse(str,1,4);
- } catch (Exception e) {
- System.out.println(e.getMessage());
- return;
- }
- System.out.println("交换后====");
- System.out.println(str);
-
- }
- //编写一个将字符串中一段字符反转的方法
- //String 转成Char后,使用for循环交换,返回建立字符串
- //设置输入参数范围,丢出来一个异常,然后try-catch处理
- public static String reverse(String str, int start,int end){
- if (!(str != null && start >= 0 && start < end && 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);
-
- }
- }
-
-
-