本文实例为大家分享了java字符串反转的具体代码,供大家参考,具体内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
import java.util.Stack;
public class StringReverse {
// 使用内置类(StringBuilder或StringBuffer)
public static String reverse1(String s) {
// StringBuilder strBuilder = new StringBuilder(s);
// String ret = strBuilder.reverse().toString();
StringBuffer strBuf = new StringBuffer(s);
String ret = strBuf.reverse().toString();
return ret;
}
// 有左到右 拼接字符串
public static String reverse2(String s) {
String ret = "" ;
for ( int i = 0 ; i < s.length(); ++i) {
ret = s.charAt(i) + ret;
}
return ret;
}
// 从右到左 拼接字符串
public static String reverse3(String s) {
String ret = "" ;
for ( int i = s.length() - 1 ; i >= 0 ; --i) {
ret += s.charAt(i);
}
return ret;
}
public static String reverse4(String s) {
String ret = "" ;
char [] charArr = s.toCharArray();
int len = charArr.length;
for ( int i = 0 ; i < len / 2 ; ++i) {
char tmp = charArr[i];
charArr[i] = charArr[len - 1 - i];
charArr[len - 1 - i] = tmp;
}
ret = new String(charArr);
return ret;
}
// 使用异或
public static String reverse5(String s) {
String ret = "" ;
char [] charArr = s.toCharArray();
int begin = 0 , end = charArr.length - 1 ;
while (begin < end) {
charArr[begin] = ( char ) (charArr[begin] ^ charArr[end]);
charArr[end] = ( char ) (charArr[begin] ^ charArr[end]);
charArr[begin] = ( char ) (charArr[begin] ^ charArr[end]);
begin++;
end--;
}
ret = new String(charArr);
return ret;
}
// 使用栈
public static String reverse6(String s) {
String ret = "" ;
Stack<Character> stack = new Stack<Character>();
for ( int i = 0 ; i < s.length(); ++i) {
stack.push(s.charAt(i));
}
while (!stack.isEmpty()) {
ret += stack.pop();
}
return ret;
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。