字符串的反转

时间:2022-01-11 17:00:40

jdk的方法:

1 String str = “abcdef”; 
2 str = new StringBuilder(str).reverse().toString();

自己实现:

 1 public class StringDemo{
2 public static void main(String[] args) {
3 System.out.println(reverse("Hello World!"));//!dlroW olleH
4 }
5 public static String reverse(String str){
6 char [] arrs = str.toCharArray();
7 char temp = ' ';
8 for(int i = 0, j = arrs.length-1; i < j; i++,j--){
9 temp = arrs[i];
10 arrs[i] = arrs[j];
11 arrs[j] = temp;
12 }
13 StringBuilder sb = new StringBuilder();
14 for(char s : arrs){
15 sb.append(s);
16 }
17 return sb.toString();
18 }
19 }
20
21 public void reverse2(final String str){
22 char [] chars = str.toCharArray();
23 StringBuilder sb = new StringBuilder();
24 for(int i = chars.length-1;i>0; i--){
25 sb.append(char[i]);
26 }
27 return sb.toString();
28 }

 

* “I love china”, 把字符反转后变成 “china love I”
方法一:一个字符一个字符的换

 1 public class StringReverse {
2
3 public void swap(char[] arr, int begin, int end) {
4 while(begin < end) {
5 char temp = arr[begin];
6 arr[begin] = arr[end];
7 arr[end] = temp;
8 begin++;
9 end--;
10 }
11 }
12 public String swapWords(String str) {
13 char[] arr = str.toCharArray();
14 swap(arr, 0, arr.length - 1);
15 int begin = 0;
16 for (int i = 1; i < arr.length; i++) {
17 if (arr[i] == ' ') {
18 swap(arr, begin, i - 1);
19 begin = i + 1;
20 }
21 }
22
23 return new String(arr);
24 }
25 public static void main(String[] args) {
26 String str = "I love java";
27 System.out.println(new StringReverse().swapWords(str));
28 }
29 }


方法二:(利用jdk提供的方法)

 1 public class Main {
2 public static void main(String[] args) {
3 Scanner sc = new Scanner(System.in);
4 String str = sc.nextLine();
5 String[] sArr = str.split(" ");//I love java
6 List<String> list = Arrays.asList(sArr);
7 Collections.reverse(list);
8 for(String word:list){
9 System.out.print(word+" ");
10 }
11 }
12 }

方法3:一个单词一个单词地换

 1 public class StringDemo{
2 public static void main(String[] args) {
3 System.out.println(reverse("Hello World!"));//World! Hello
4 }
5 public static String reverse(String str){
6 String [] arrs = str.split(" ");
7 String temp = "";
8 for(int i = 0, j = arrs.length-1; i < j; i++, j--){
9 temp = arrs[i];
10 arrs[i] = arrs[j];
11 arrs[j] = temp;
12 }
13 StringBuilder sb = new StringBuilder();
14 for(String s : arrs){
15 sb.append(s).append(" ");
16 }
17 return sb.toString();
18 }
19 }