Advertisement
Advertisement


Reverse a string in Java


Question

I have "Hello World" kept in a String variable named hi.

I need to print it, but reversed.

How can I do this? I understand there is some kind of a function already built-in into Java that does that.

Related: Reverse each individual word of “Hello World” string with Java

2017/09/10
1
477
9/10/2017 9:38:14 PM

Accepted Answer

You can use this:

new StringBuilder(hi).reverse().toString()

Or, for versions earlier than JDK 1.5, use java.util.StringBuffer instead of StringBuilder — they have the same API. Thanks commentators for pointing out that StringBuilder is preferred nowadays when there is no concurrency concern.

2019/02/07
998
2/7/2019 2:49:13 PM

For Online Judges problems that does not allow StringBuilder or StringBuffer, you can do it in place using char[] as following:

public static String reverse(String input){
    char[] in = input.toCharArray();
    int begin=0;
    int end=in.length-1;
    char temp;
    while(end>begin){
        temp = in[begin];
        in[begin]=in[end];
        in[end] = temp;
        end--;
        begin++;
    }
    return new String(in);
}
2018/02/28

public static String reverseIt(String source) {
    int i, len = source.length();
    StringBuilder dest = new StringBuilder(len);

    for (i = (len - 1); i >= 0; i--){
        dest.append(source.charAt(i));
    }

    return dest.toString();
}

http://www.java2s.com/Code/Java/Language-Basics/ReverseStringTest.htm

2014/11/11

String string="whatever";
String reverse = new StringBuffer(string).reverse().toString();
System.out.println(reverse);
2011/09/27

I am doing this by using the following two ways:

Reverse string by CHARACTERS:

public static void main(String[] args) {
    // Using traditional approach
    String result="";
    for(int i=string.length()-1; i>=0; i--) {
        result = result + string.charAt(i);
    }
    System.out.println(result);

    // Using StringBuffer class
    StringBuffer buffer = new StringBuffer(string);
    System.out.println(buffer.reverse());    
}

Reverse string by WORDS:

public static void reverseStringByWords(String string) {
    StringBuilder stringBuilder = new StringBuilder();
    String[] words = string.split(" ");

    for (int j = words.length-1; j >= 0; j--) {
        stringBuilder.append(words[j]).append(' ');
    }
    System.out.println("Reverse words: " + stringBuilder);
}
2017/11/15

Take a look at the Java 6 API under StringBuffer

String s = "sample";
String result = new StringBuffer(s).reverse().toString();
2011/09/27

Source: https://stackoverflow.com/questions/7569335
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]