欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 其中翻转字符串的实现方法

程序员文章站 2024-02-22 17:58:10
给大家介绍其中常用和不常用的将字符串翻转过来的方法: 复制代码 代码如下:import java.util.stack; public class stringrev...

给大家介绍其中常用和不常用的将字符串翻转过来的方法:

复制代码 代码如下:

import java.util.stack;

public class stringreverse {

public static string reverse1(string s) {

   int length = s.length();

   if (length <= 1)

    return s;

   string left = s.substring(0, length / 2);

   string right = s.substring(length / 2, length);

   return reverse1(right) + reverse1(left);

 }

 public static string reverse2(string s) {

   int length = s.length();

   string reverse = "";

   for (int i = 0; i < length; i++)

    reverse = s.charat(i) + reverse;

   return reverse;

  }

  public static string reverse3(string s) {

   char[] array = s.tochararray();

   string reverse = "";

   for (int i = array.length - 1; i >= 0; i--)

    reverse += array[i];

   return reverse;

  }

  public static string reverse4(string s) {

   return new stringbuffer(s).reverse().tostring();

  }

  public static string reverse5(string orig) {

   char[] s = orig.tochararray();

   int n = s.length - 1;

   int halflength = n / 2;

   for (int i = 0; i <= halflength; i++) {

    char temp = s[i];

    s[i] = s[n - i];

    s[n - i] = temp;

   }

   return new string(s);

  }

  public static string reverse6(string s) {

   char[] str = s.tochararray();

   int begin = 0;

   int end = s.length() - 1;

   while (begin < end) {

    str[begin] = (char) (str[begin] ^ str[end]);

    str[end] = (char) (str[begin] ^ str[end]);

    str[begin] = (char) (str[end] ^ str[begin]);

    begin++;

    end--;

   }

   return new string(str);

  }

  public static string reverse7(string s) {

   char[] str = s.tochararray();

   stack<character> stack = new stack<character>();

   for (int i = 0; i < str.length; i++)

    stack.push(str[i]);

   string reversed = "";

   for (int i = 0; i < str.length; i++)

    reversed += stack.pop();

   return reversed;

  }

 }