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

时间:2021-05-20

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

复制代码 代码如下:
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;

}

}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章