Java反转字符串的10种方法(代码段)

2018-11-22    来源:importnew

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

在这篇文章中,我们会讨论10种用Java反转字符串的方法,通过10个Java程序反转字符串。例如,把字符串“javaguides” 反转为 “sediugavaj”。

1. 使用 + (String连接) 操作符

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseWithStringConcat {
    public static void main(String[] args) {
        ReverseWithStringConcat concat = new ReverseWithStringConcat();
        concat.reverseWithStringConcat("javaguides");
    }
    private String reverseWithStringConcat(String input) {
        String output = new String();
        for (int i = (input.length() - 1); i >= 0; i--) {
            output += (input.charAt(i));
        }
        display(input, output);
        return output;
    }
    private void display(String input, String output) {
        System.out.println(" input string :: " + input);
        System.out.println(" output string :: " + output);
    }
}

输出:

 input string :: javaguides
 output string :: sediugavaj

2. 使用 StringBuilder

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseWithStringBuilderBuiltinMethod {
    public static void main(String[] args) {
        ReverseWithStringBuilderBuiltinMethod builtinMethod = new ReverseWithStringBuilderBuiltinMethod();
        builtinMethod.reverseWithStringBuilderBuiltinMethod("javaguides");
    }
    public String reverseWithStringBuilderBuiltinMethod(String string) {
        final StringBuilder builder = new StringBuilder(string);
        display(string, builder.reverse().toString());
        return builder.reverse().toString();
    }
    private void display(String input, String output) {
        System.out.println(" input string :: " + input);
        System.out.println(" output string :: " + output);
    }
}

输出:

 input string :: javaguides
 output string :: sediugavaj

3. 使用 String charAt 方法

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseWithStringChatAt{
    public static void main(String[] args) {
        ReverseWithStringChatAt reverseWithStringBuilder = new ReverseWithStringChatAt();
        reverseWithStringBuilder.reverseWithStringBuilder("javaguides");
    }
    public String reverseWithStringChatAt(String string) {
        final StringBuilder builder = new StringBuilder();
        for (int i = (string.length() - 1); i >= 0; i--) {
            builder.append(string.charAt(i));
        }
        display(string, builder.toString());
        return builder.toString();
    }
    private void display(String input, String output) {
        System.out.println(" input string :: " + input);
        System.out.println(" output string :: " + output);
    }
}

输出:

 input string :: javaguides
 output string :: sediugavaj

4. 通过交换字符反转

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseStringWithSwaps {
    public static void main(String[] args) {
        ReverseStringWithSwaps stringWithSwaps = new ReverseStringWithSwaps();
        stringWithSwaps.reverseWithSwaps("javaguides");
    }
    public String reverseWithSwaps(String string) {
        final char[] array = string.toCharArray();
        final int length = array.length - 1;
        final int half = (int) Math.floor(array.length / 2);
        char c;
        for (int i = length; i >= half; i--) {
            c = array[length - i];
            array[length - i] = array[i];
            array[i] = c;
        }
        display(string, String.valueOf(array));
        return String.valueOf(array);
    }
    private void display(String input, String output) {
        System.out.println(" input string :: " + input);
        System.out.println(" output string :: " + output);
    }
}

输出:

 input string :: javaguides
 output string :: sediugavaj

5. 使用 XOR(^) 操作符反转

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseStringWithXOR {
    public static void main(String[] args) {
        ReverseStringWithXOR stringWithXOR = new ReverseStringWithXOR();
        stringWithXOR.reverseWithXOR("javaguides");
    }
    public String reverseWithXOR(String string) {
        final char[] array = string.toCharArray();
        final int length = array.length;
        final int half = (int) Math.floor(array.length / 2);
        for (int i = 0; i < half; i++) {
            array[i] ^= array[length - i - 1];
            array[length - i - 1] ^= array[i];
            array[i] ^= array[length - i - 1];
        }
        display(string, String.valueOf(array));
        return String.valueOf(array);
    }
    private void display(String input, String output) {
        System.out.println(" input string :: " + input);
        System.out.println(" output string :: " + output);
    }
}

输出:

 input string :: javaguides
 output string :: sediugavaj

6. 使用堆栈

package net.javaguides.corejava.string;
import java.util.Stack;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseStringUsingStack {
    // Function to reverse a string in Java using a stack and character array
    public static String reverse(String str) {
        // base case: if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // create an empty stack of characters
        Stack < Character > stack = new Stack < Character > ();
        // push every character of the given string into the stack
        char[] ch = str.toCharArray();
        for (int i = 0; i < str.length(); i++)
            stack.push(ch[i]);
        // start from index 0
        int k = 0;
        // pop characters from the stack until it is empty
        while (!stack.isEmpty()) {
            // assign each popped character back to the character array
            ch[k++] = stack.pop();
        }
        // convert the character array into string and return it
        return String.copyValueOf(ch);
    }
    public static void main(String[] args) {
        String str = "javaguides";
        str = reverse(str); // string is immutable
        System.out.println("Reverse of the given string is : " + str);
    }
}

输出:

Reverse of the given string is : sediugavaj

7. 使用 Collections reverse() 方法

package net.javaguides.corejava.string;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseStringUsingCollectionsReverseMethod {
    // Function to reverse a string in Java using Collections.reverse()
    public static String reverse(String str) {
        // base case: if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // create an empty list of characters
        List < Character > list = new ArrayList < Character > ();
        // push every character of the given string into it
        for (char c: str.toCharArray())
            list.add(c);
        // reverse list using java.util.Collections reverse()
        Collections.reverse(list);
        // covert ArrayList into String using StringBuilder and return it
        StringBuilder builder = new StringBuilder(list.size());
        for (Character c: list)
            builder.append(c);
        return builder.toString();
    }
    public static void main(String[] args) {
        String str = "Java Guides";
        // String is immutable
        str = reverse(str);
        System.out.println("Reverse of the given string is : " + str);
    }
}

输出:

Reverse of the given string is : sediuG avaJ

8. 使用 Byte 数组

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class ReverseStringUsingByteArray {
    // Function to reverse a string in Java using byte array
    public static String reverse(String str) {
        // return if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // convert string into bytes
        byte[] bytes = str.getBytes();
        // start from the two end points l and h of the given string
        // and increment l & decrement h at each iteration of the loop
        // until two end-points intersect (l >= h)
        for (int l = 0, h = str.length() - 1; l < h; l++, h--) {
            // Swap values at l and h
            byte temp = bytes[l];
            bytes[l] = bytes[h];
            bytes[h] = temp;
        }
        // convert byte array back into the string
        return new String(bytes);
    }
    public static void main(String[] args) {
        String str = "Java Guides";
        // String is immutable
        str = reverse(str);
        System.out.println("Reverse of the given string is : " + str);
    }
}

输出:

Reverse of the given string is : sediuG avaJ

9. 使用 substring() 方法

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class UsingSubStringFunction {
    // Function to reverse a string in Java using recursion
    private static String reverse(String str) {
        // base case: if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // last character + recurse for remaining string
        return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
    }
    public static void main(String[] args) {
        String str = "javaguides";
        // string is immutable
        str = reverse(str);
        System.out.println("Reverse of the given string is : " + str);
    }
}

输出:

Reverse of the given string is : sediugavaj

10. 使用递归

package net.javaguides.corejava.string;
/**
 * 
 * @author Ramesh Fadatare
 *
 */
public class UsingRecursion {
    static int i = 0;
    // Recursive function to reverse a string in Java using static variable
    private static void reverse(char[] str, int k) {
        // if we have reached the end of the string
        if (k == str.length)
            return;
        // recurse for next character
        reverse(str, k + 1);
        if (i <= k) {
            char temp = str[k];
            str[k] = str[i];
            str[i++] = temp;
        }
    }
    public static String reverse(String str) {
        // base case: if string is null or empty
        if (str == null || str.equals(""))
            return str;
        // convert string into a character array
        char[] A = str.toCharArray();
        // reverse character array
        reverse(A, 0);
        // convert character array into the string
        return String.copyValueOf(A);
    }
    public static void main(String[] args) {
        String str = "Java Guides";
        // string is immutable
        str = reverse(str);
        System.out.println("Reverse of the given string is : " + str);
    }
}

输出:

Reverse of the given string is : sediuG avaJ

String 相关文章

  1. Java String Class API 指南
  2. Java String 常量池指南
  3. Java String 方法实例
  4. Java String 最佳实践
  5. String 特殊操作符实例
  6. String 比较函数实例
  7. String 字符提取函数
  8. String 搜索函数实例
  9. String 修改函数实例
  10. Java StringBuffer Class API 指南
  11. Java StringBuilder Class 方法
  12. Java StringBuffer Class 方法
  13. Java StringBuilder Class API 指南
  14. Java 8 StringJoiner Class
原文链接: dzone 翻译: ImportNew.com - 唐尤华
译文链接: http://www.importnew.com/30579.html
[ 转载请保留原文出处、译者和译文链接。]

关于作者: 唐尤华

唐尤华

我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其实我是一个程序员。(新浪微博:@唐尤华

查看唐尤华的更多文章 >>

标签: isp swap 搜索

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Java调试检查表

下一篇:谈谈 Java 类加载机制