本文主要讲述java中的字符串反转
示例代码如下:
1 public class HomeWork01 { 2 public static void main(String[] args) { 3 String s = "abcdef"; 4 // edcbaf 5 String reverse = null; 6 try { 7 reverse = reverse(s, -01, 4); 8 System.out.println(reverse); 9 } catch (RuntimeException e) { 10 System.out.println(e.getMessage()); 11 } 12 } 13 14 // 指定位置开始反转字符串 15 public static String reverse(String str,int start,int end) { 16 if(str == null){ 17 throw new RuntimeException("str不能为空串"); 18 } 19 if(start < 0){ 20 throw new RuntimeException("start输入错误"); 21 } 22 if(end >= str.length()){ 23 throw new RuntimeException("end不能超过str的长度"); 24 } 25 if(start >= end){ 26 throw new RuntimeException("start比end小,无法反转"); 27 } 28 char[] chars = str.toCharArray(); 29 for(int i = start,j = end;i < j;i++,j--){ 30 char ch = chars[i]; 31 chars[i] = chars[j]; 32 chars[j] = ch; 33 } 34 String s = new String(chars); 35 return s; 36 37 } 38 }
标签:end,String,RuntimeException,反转,chars,start,str,字符串,java From: https://www.cnblogs.com/zwgitOne123/p/17013508.html