Easy way to reverse String

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

提交回复
热议问题