1 package wang.yong.x; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.Collections; 6 import java.util.List; 7 8 // 写一个方法将字符串中的单词倒序,例如:"tom is cat"倒序结果为"cat is tom" 9 public class Test2 { 10 public static void main(String[] args) { 11 String str = "tom is cat"; 12 // String str2 = m(str); 13 // System.out.println("str2 = "+str2); 14 System.out.println("=========="); 15 System.out.println("str2 = "+n(str)); 16 System.out.println("=========="); 17 System.out.println(w(str)); 18 } 19 20 // ArrayList的存入和取出顺序一直 21 public static String w(String str){ 22 String[] string = str.split(" "); 23 String str2 = ""; 24 List<String> list = new ArrayList<>(); 25 for(int i = string.length-1;i>=0;i--){ 26 list.add(string[i]); 27 str2+=string[i]+" "; 28 } 29 //string = list.toArray(string); 30 //return Arrays.toString(string); 31 return str2; 32 } 33 34 // 直接数组元素对换 35 public static String n(String str){ 36 String[] string = str.split(" "); 37 String str2 = ""; 38 for(int start =0, end=string.length-1;start<end;start++,end--){ 39 String temp = string[end]; 40 string[end] = string[start]; 41 string[start] = temp; 42 } 43 for(int i = 0;i<string.length;i++){ 44 str2+=string[i]+" "; 45 } 46 return str2; 47 } 48 49 // 使用collections和Arrays工具类 50 public static String m(String str){ 51 String[] string = str.split(" "); 52 Collections.reverse(Arrays.asList(string)); 53 String str2=""; 54 for(int i=0;i<string.length;i++){ 55 str2=str2+string[i]+" "; 56 } 57 return str2; 58 } 59 }