关于字符串翻转的几种方法

import java.util.ArrayList;

/**
 * Created by d007l on 2017/3/12.
 */
public class ReverseTest {
    public static void main(String[] args){

        String str = "偷得浮生半日闲";
        System.out.println("翻转前的字符串展示是:\n" + str);
        System.out.println("翻转后的字符串展示是:\n" + myTurn(str));
        reverse(str);
        myReverse(str);

    }
    //利用ArrayList,如果讲究格式的话,需要复写一下toString方法
    public static ArrayList  myTurn(String str){
        char[] arr = str.toCharArray();
        ArrayList list = new ArrayList();
        for(int i = arr.length -1;i>=0;i--){
            list.add(arr[i]);
        }
        return list;
    }
    //该方法是直接进行字符数组赋值
    public static void reverse(String str){
        char[] arr = str.toCharArray();
        char[] newArr = new char[arr.length];
        int index = 0;
        while (index < arr.length){
            newArr[arr.length-index-1] = arr[index];
            index++;
        }
        System.out.println();
        for(char c :newArr)
            System.out.print(c);
    }
    //StringBuilder,字符串缓冲类
    public static StringBuilder myReverse(String str){
        char[] arr = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i < arr.length;i++){
            sb.append(arr[i]);
        }
        return sb;
    }
}

你可能感兴趣的:(java基础)