您的位置:首页 > 编程语言 > Java开发

7 种将字符串反转的 Java 方法

2013-11-04 15:32 465 查看

01
import
java.util.Stack;
02
public
class
StringReverse{
03
04
public

static
Stringreverse1(Strings){
05
int

length=s.length();
06
if

(length<=
1
)
07
return

s;
08
Stringleft=s.substring(
0
,length/
2
);
09
Stringright=s.substring(length/
2
,length);
10
return

reverse1(right)+reverse1(left);
11
}
12
13
public

static
Stringreverse2(Strings){
14
int

length=s.length();
15
Stringreverse=
""
;
16
for

(
int

i=
0
;i<length;i++)
17
reverse=s.charAt(i)+reverse;
18
return

reverse;
19
}
20
21
public

static
Stringreverse3(Strings){
22
char
[]array=s.toCharArray();
23
Stringreverse=
""
;
24
for

(
int

i=array.length-
1
;i>=
0
;i--)
25
reverse+=array[i];
26
27
return

reverse;
28
}
29
30
public

static
Stringreverse4(Strings){
31
return

new
StringBuffer(s).reverse().toString();
32
}
33
34
public

static
Stringreverse5(Stringorig){
35
char
[]s=orig.toCharArray();
36
int

n=s.length-
1
;
37
int

halfLength=n/
2
;
38
for

(
int

i=
0
;i<=halfLength;i++){
39
char

temp=s[i];
40
s[i]=s[n-i];
41
s[n-i]=temp;
42
}
43
return

new
String(s);
44
}
45
46
public

static
Stringreverse6(Strings){
47
48
char
[]str=s.toCharArray();
49
50
int

begin=
0
;
51
int

end=s.length()-
1
;
52
53
while

(begin<end){
54
str[begin]=(
char
)(str[begin]^str[end]);
55
str[end]=(
char
)(str[begin]^str[end]);
56
str[begin]=(
char
)(str[end]^str[begin]);
57
begin++;
58
end--;
59
}
60
61
return

new
String(str);
62
}
63
64
public

static
Stringreverse7(Strings){
65
char
[]str=s.toCharArray();
66
Stack<Character>stack=
new
Stack<Character>();
67
for

(
int

i=
0
;i<str.length;i++)
68
stack.push(str[i]);
69
70
Stringreversed=
""
;
71
for

(
int

i=
0
;i<str.length;i++)
72
reversed+=stack.pop();
73
74
return

reversed;
75
}
76
77
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: