Easy way to reverse String

后端 未结 12 1040
野性不改
野性不改 2021-02-13 04:01

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

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

    You may use StringBuilder..

    String word = "Hello World!";
    StringBuilder sb = new StringBuilder(word);
    
    System.out.print(sb.reverse());
    
    0 讨论(0)
  • 2021-02-13 04:26

    Use StringBuilder's or StringBuffer's method... reverse()

     public class StringReverse
    {
      public static void main(String[] args)
      {
      String string=args[0];
      String reverse = new StringBuffer(string).reverse().toString();
      System.out.println("\nString before reverse: "+string);
      System.out.println("String after reverse: "+reverse);
      } 
    } 
    

    StringBuffer is thread-safe, where as StringBuilder is Not thread safe..... StringBuilder was introduced from Java 1.5, as to do those operations faster which doesn't have any Concurrency to worry about....

    0 讨论(0)
  • 2021-02-13 04:26

    Try reverse() method:

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

    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:29

    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:31

    Here I have a sample of the same using substring method and o(n) without using any nethods from string . I am aware that using substring will hold complete string memory.

    for(int i = 0; i < s.length(); i++)    {
        s = s.substring(1, s.length() - i) + s.charAt(0) + s.substring(s.length() - i);
        System.out.println(s);
    }
    

    This might help you!!

    0 讨论(0)
提交回复
热议问题