当前位置:主页 > 软件编程 > JAVA代码 >

Java实现字符串反转

时间:2022-07-04 14:07:20 | 栏目:JAVA代码 | 点击:

第一种:

public class Main {

    public static void main(String[] args) {
        String s1 = "asdfghjkl";
        System.out.println(new StringBuilder(s1).reverse().toString());
    }
}

第二种:

public class Main {

    public static void main(String[] args) {
        String s1 = "asdfghjkl";
        String[] s = s1.split("");
        List<String> list = list = Arrays.asList(s);
        Collections.reverse(list);
        System.out.println(list);
    }
}

第三种:

public class Main {

    public static void main(String[] args) {
        String s1 = "asdfghjkl";        System.out.println(new Main().swapWords(s1));

    }

    public void swap(char[] arr, int begin, int end) {
        while (begin < end) {
            char temp = arr[begin];
            arr[begin] = arr[end];
            arr[end] = temp;
            begin++;
            end--;
        }
    }

    public String swapWords(String str) {
        char[] arr = str.toCharArray();
        swap(arr, 0, arr.length - 1);
        int begin = 0;
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] == ' ') {
                swap(arr, begin, i - 1);
                begin = i + 1;
            }
        }
        return new String(arr);
    }
}

您可能感兴趣的文章:

相关文章