system_esc

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 将一个字符串进行反转或者字符串中指定部分进行反转

 思路:

  将字符串变成数组,对数组反转
    将反转后的数组变成字符串
    只要将反转的部分的开始和结束的位置作为参数传递即可

复制代码
 1 class reverse_String{
 2     public static void main (String[] args){
 3         String s1 = "      java php .net    ";
 4         String s2 = reverseString(s1);
 5         System.out.println(s2);
 6     }
 7     public static void reverseString(String str, int start, int end){
 8         char[] chs = str.toCharArray();//字符串变数组
9
10 reverseArray(chs,start,end);//反转数组
11 12 retrun new String(chs);//将数组变字符串
13 } 14 public static void reverseString(String str){ 15 retrun reverseString(str,0,str.length()); 16 } 17 18 public static void reverseArray(char[] arr,int x , int y){ 19 for(int start = x,end=y-1; start<end; start++,end--){ 20 swap(arr,start,end); 21 } 22 } 23 private static void swap(char[] arr,int x ,int y){ 24 char temp = arr[x]; 25 arr[x] = arr[y]; 26 arr[y] = temp; 27 } 28 29 }
posted on 2014-01-13 15:38  system_esc  阅读(218)  评论(0编辑  收藏  举报