将字符串反转

将一个字符串进行反转或者字符串中指定部分进行反转

 思路:

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

public class Test_of {

    

    public static void main(String[] args){

        String s = "   huangjiafeng   ";

        s = reverseString(s,3,5);

        System.out.println(s);

    }

    public static String reverseString(String str,int start,int end){

        char[] chs = str.toCharArray();

        

        reverseArray(chs,start,end);

        

        return String.valueOf(chs);

    }

    

    public static String reverseString(String str){

        return reverseString(str,0,str.length()-1);

    }

    

    private static void reverseArray(char[] chs,int x,int y) {

        for (int start = x,end = y; start<end;start++,end--) {

            swap(chs,start,end);

            

        }

    }

    private static void swap(char[] chs, int start, int end) {

        char temp = chs[start];

        chs[start] = chs[end];

        chs[end] = temp;

        

    }

    

}

 

你可能感兴趣的:(字符串)