Printing reverse of any String without using any predefined function?

后端 未结 30 1333
生来不讨喜
生来不讨喜 2020-11-30 03:08

How to print the reverse of the String java is object orientated language without using any predefined function like reverse()?

30条回答
  •  迷失自我
    2020-11-30 03:20

    I had this a while back, and having answered with the obvious StringBuffer.reverse() answer, they then asked 'Can you reverse a char array without using those API methods and achieve the result without spooling into a new char array?'

    At the time I recognised that I only needed to iterate over half the length of the char array, but made a bit of a hash of explaining the actual code that needed to go into it (it was a verbal question). Anyway, I tried it when I got home and came up with this:

    public class StringReverse {
    
    public static void main(String[] args){
    
        String a = "String";
    
        char[] aChar = a.toCharArray();
    
        for (int i = (aChar.length-1)/2 ; i >= 0 ; i--){
            int posA = i;
            int posB = (aChar.length-1-i);
            char tmpA = aChar[posA];
            char tmpB = aChar[posB];
            System.out.println("Setting " + posA + " to " + tmpB);
            System.out.println("Setting " + posB + " to " + tmpA);
    
            aChar[posA] = tmpB;
            aChar[posB] = tmpA;
        }
    
        System.out.println(aChar);
    }
    
    }
    

    You can obviously achieve this with less code, but I think the temporary assignments in the method make it more clear what the code is doing.

    Outputs something like:

    Setting 2 to i
    Setting 3 to r
    Setting 1 to n
    Setting 4 to t
    Setting 0 to g
    Setting 5 to S
    
    gnirtS
    

    More of an interview question than a homework question, I'd say.

提交回复
热议问题