String algorithms practice of reverse

JavaScript版:

function reverseString(str) {
    arr = str.split('');//转换为字符数组
    arr2 = arr.reverse();
    str = arr2.join('');//字符数组转换为字符串
    return str;
}

reverseString("hello");

java version:

//法1:利用StringBuffer/StringBuilder的reverse方法
public class Test {
    public static void main(String[] args) {
        String str = "Hello World";
        StringBuffer s = new StringBuffer(str);
        s.reverse();
        System.out.println(s);//dlroW olleH

    }
}
//法2:转换为字符数字遍历反向赋值给一个字符串类型变量
public class Test {
    public static void main(String[] args) {
        String str = "Hello World";
        char[] chars = str.toCharArray();
        String s = "";
        for (int i = chars.length-1; i >= 0 ; i--) {
            s += chars[i];
        }
        System.out.println(s);//dlroW olleH
    }
}

java version of the more visible method: the Java or 9 to achieve eight kinds of ways to reverse a string

Published 95 original articles · won praise 43 · views 70000 +

Guess you like

Origin blog.csdn.net/lyxuefeng/article/details/94630777