Java重修笔记 第三十八天 String翻转
-
String翻转
1. 要求将字符串指定的部分进行翻转
public class StringHomework {public static void main(String[] args) {// 要求将字符串指定的部分进行翻转// 例如:abcdef ---> a edcb f 1, 4System.out.print("转换前: ");String s = "abcdef";String s1 = null;System.out.println(s);try {System.out.println("=========");System.out.print("转换后: ");System.out.println(StringHomework.reverse(s, 1, 4));} catch (NullPointerException e) {System.out.println(e.getMessage() + "传入的字符串为null!");}}public static String reverse(String str, int start, int end) throws NullPointerException{// 先将字符串转换为字符数组char[] chars = str.toCharArray();// 判断 str 是否合法if (str.isEmpty()) {throw new RuntimeException("传入的字符串数据不合法!");}// 判断 start 和 end 是否合法if (start < 0 || end > chars.length || start > end) {throw new RuntimeException("传入的起始位置数据不合法!");}// 进行数组翻转, 提取出要反转的部分char[] chars1 = new char[end - start + 1];System.arraycopy(chars, start, chars1, 0, chars1.length);// return new String(chars1);// 翻转 chars1 字符数组for (int i = 0; i < chars1.length / 2; i++) {char temp = chars1[i];chars1[i] = chars1[chars1.length - i - 1];chars1[chars1.length - i - 1] = temp;}// return new String(chars1);// 将原数组数据替换System.arraycopy(chars1, 0, chars, start, chars1.length);return new String(chars);}
}
运行结果: