Blog

It's a Wonderful Life

java中字符串翻转的几种实现

2017-04-21 12:16 Posted in Learn with Java

java面试中经常会考到字符串翻转的函数,这里写出几种实现方法。

import java.io.PrintStream;

public class Strrev
{
    public static void main(String[] args)
    {
        String test = "abcdefg";
        rev1(test);
        rev2(test);
        rev3(new StringBuilder(test), new StringBuilder(), test.length() - 1);
    }
    
    public static void rev1(String str)
    {
        StringBuilder sb = new StringBuilder(str);
        sb.reverse();
        System.out.println(sb.toString());
    }
    
    public static void rev2(String str)
    {
        StringBuilder sb = new StringBuilder(str);
        StringBuilder revSb = new StringBuilder();
        for (int i = sb.length() - 1; i >= 0; i--)
        {
            revSb.append(sb.charAt(i));
        }
        System.out.println(revSb.toString());
    }
    
    public static void rev3(StringBuilder sb, StringBuilder revSb, int index)
    {
        if (index < 0)
        {
            System.out.println(revSb.toString());
            return;
        }
        
        revSb.append(sb.charAt(index));
        index -= 1;
        rev3(sb, revSb, index);
    }
}