Easy way to reverse String

后端 未结 12 1026
野性不改
野性不改 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:31

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

    Try this,

    String s = "responses";
    StringBuilder builder = new StringBuilder(s);
    System.out.println(builder.reverse());
    
    0 讨论(0)
  • 2021-02-13 04:33

    You can use the StringBuilder#reverse() method:

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

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

    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)
  • 2021-02-13 04:48
    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)
提交回复
热议问题