Easy way to reverse String

后端 未结 12 2495
北荒
北荒 2021-02-13 03:47

Without going through the char sequence is there any way to reverse String in Java

相关标签:
12条回答
  • 2021-02-13 04:21

    You can use the StringBuilder#reverse() method:

    String reverse = new StringBuilder(originalString).reverse().toString();
    
    0 讨论(0)
  • 2021-02-13 04:21

    Try reverse() method:

    StringBuilder stringName = new StringBuilder();
    String reverse = stringName.reverse().toString();
    
    0 讨论(0)
  • 2021-02-13 04:21

    If we have to do it:

    Without going through the char sequence

    One easy way with iteration will be:

    public String reverse(String post) {                
        String backward = "";
        for(int i = post.length() - 1; i >= 0; i--) {
            backward += post.substring(i, i + 1);
        }        
        return backward;
    } 
    
    0 讨论(0)
  • 2021-02-13 04:23

    Using minimal API support. A simple algorithm.

    static String reverse(String str) {
        char[] buffer = str.toCharArray();
        for (int i = 0; i < buffer.length/2; ++i){
            char c = buffer[i];
            buffer[i] = buffer[buffer.length-1-i];
            buffer[buffer.length-1-i] = c;
        }
        return new String(buffer);
    }
    
    0 讨论(0)
  • 2021-02-13 04:34
    public class RevString {
      public static void main(String[] args) {
        String s="jagan";
        String rev="";
        for (int i=s.length()-1;i>=0;i--) {
          rev=rev+s.charAt(i);
        }
         System.out.println("Reverse String is: "+rev);
      }
    }
    
    0 讨论(0)
  • 2021-02-13 04:35

    Try this,

    String s = "responses";
    StringBuilder builder = new StringBuilder(s);
    System.out.println(builder.reverse());
    
    0 讨论(0)
提交回复
热议问题