DEV Community

永鹏 徐
永鹏 徐

Posted on

How to reverse a string in java

mark:reverse a string by build-in function chartAt

private String reverseString2(String str) {
    if (str == null) {
        return null;
    }
    String result = "";
    for (int i = str.length() - 1; i >= 0; i--) {
        result = result + str.charAt(i);
    }
    return result;
}

public void test(){
    System.out.println(reverseString2("abcd"));
}
Enter fullscreen mode Exit fullscreen mode

also can see reverse-a-string-in-java

Top comments (1)

Collapse
 
vinny627 profile image
Vinicius Duarte

I use StringBuilder, looks simpler:
new StringBuilder("esrever").reverse().toString()