Easy way to reverse String

后端 未结 12 2496
北荒
北荒 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:35

    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)
  • 2021-02-13 04:43

    I have not seen any easy way. Here is the suitable way to do:


    Using the loop:


        String d = "abcdefghij";
        char b[] = new char[d.length()];// new array;
        int j=0; // for the array indexing
        for(int i=d.length()-1;i>=0;i--){
            b[j] = d.charAt(i); // input the last value of d in first of b i.e. b[0] = d[n-1]
            j++;
        }
        System.out.println("The reverse string is: "+String.valueOf(b));
    


    Output is The reverse string is: jihgfedcba
    The simple logic is:

    array[i] = array[n-i]; where i is the Iteration and n is the total length of array

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

    This is a way to do so using recursion -

    public static String reverse(String s1){
            int l = s1.length();
            if (l>1)
                    return(s1.substring(l-1) + reverse(s1.substring(0,l-1)));
            else
                    return(s1.substring(0));
    }
    
    0 讨论(0)
  • 2021-02-13 04:45

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

    You may use StringBuilder..

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

    You can use String buffer to reverse a string.

    public String reverse(String s) {
        return new StringBuffer(s).reverse().toString();
    }
    

    one more interesting way to do this is recursion.

    public String reverse(String s) {
        if (s.length() <= 1) { 
            return s;
        }
        return reverse(s.substring(1, s.length())) + s.charAt(0);
    }
    
    0 讨论(0)
提交回复
热议问题