转载

如何在Java中使用迭代和递归反转字符串

这是在Java中使用迭代和递归反转字符串的代码示例。递归解决方案仅用于演示和教学目的,不要在生产代码中使用递归解决方案,因为如果要反转的字符串是非常长的字符串,或者您的反向函数中有任何bug,那么它可能会导致StAccOffFuffFor错误,不管怎样,这是一个很好的测试,可以让您熟悉java中的递归函数。

import java.io.FileNotFoundException;
import java.io.IOException;

/**
*
*@author Javin
/
public class StringReverseExample {

    public static void main(String args) throws FileNotFoundException, IOException {

        //original string
        String str = "Sony is going to introduce Internet TV soon";
        System.out.println("Original String: " + str);

        //reversed string using Stringbuffer
        String reverseStr = new StringBuffer(str).reverse().toString();
        System.out.println("Reverse String in Java using StringBuffer: " + reverseStr);

        //iterative method to reverse String in Java
        reverseStr = reverse(str);
        System.out.println("Reverse String in Java using Iteration: " + reverseStr);

        //recursive method to reverse String in Java
        reverseStr = reverseRecursively(str);
        System.out.println("Reverse String in Java using Recursion: " + reverseStr);

    }

    public static String reverse(String str) {
        StringBuilder strBuilder = new StringBuilder();
        char strChars = str.toCharArray();

        for (int i = strChars.length - 1; i >= 0; i--) {
            strBuilder.append(strChars[i]);
        }

        return strBuilder.toString();
    }

    public static String reverseRecursively(String str) {

        //base case to handle one char string and empty string
        if (str.length() < 2) {
            return str;
        }

        return reverseRecursively(str.substring(1)) + str.charAt(0);

    }
}[/i]

这就是如何使用递归、迭代和不使用StringBuffer来在Java中反转字符串的方法。可以借此了解程序员是否有能力理解递归问题。

原文  https://www.jdon.com/51862
正文到此结束
Loading...