Whats the best way to recursively reverse a string in Java?

后端 未结 26 2518
一个人的身影
一个人的身影 2020-11-27 14:56

I have been messing around with recursion today. Often a programming technique that is not used enough.

I set out to recursively reverse a string. Here\'s what I cam

相关标签:
26条回答
  • 2020-11-27 15:50

    function call:

        //str:string to be reversed,i=0,j=str.length-1
    
    
        public void reverseString(String str,int i,int j)
        {
    
         if(i==j)
            {
             System.out.println(str);
             return;
            }
    
         char x=str.charAt(i);
         str=str.replace(str.charAt(i),str.charAt(j));
         str=str.replace(str.charAt(j),x);
         i++;j--;
         reverseString(str,i,j);
        }
    

    this method works too..

    0 讨论(0)
  • 2020-11-27 15:51
    public class StringUtility {
    
    public static void main(String[] args) {
        StringUtility stringUtility = new StringUtility();
    
        String input = "santosh123";
        int middle = input.length() / 2;
        middle = middle - 1;
        System.out.println(stringUtility.stringReverse(input, middle));
    }
    
    public String stringReverse(String input, int middle) {
    
        if (middle == -1) {
    
            System.out.println("if");
            return input;
    
        } else {
    
            System.out.println("else");
            input = swapChar(input, middle);
            middle = middle - 1;
            return stringReverse(input, middle);
    
        }
    
    }
    
    private String swapChar(String input, int middle) {
        StringBuilder str = new StringBuilder(input);
        char begin = str.charAt(middle);
        int endIndex = input.length() - middle - 1;
        char end = str.charAt(endIndex);
        str.setCharAt(middle, end);
        str.setCharAt(endIndex, begin);
        System.out.println(str + "  " + middle + "  " + endIndex);
        return str.toString();
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题