方法一:
public class StringReverse { public void swap(char[] arr, int begin, int end) { while(begin < end) { char temp = arr[begin]; arr[begin] = arr[end]; arr[end] = temp; begin++; end--; } } //I love java public String swapWords(String str) { char[] arr = str.toCharArray(); swap(arr, 0, arr.length - 1); int begin = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] == ' ') { swap(arr, begin, i - 1); begin = i + 1; } } return new String(arr); } public static void main(String[] args) { String str = "I love java"; System.out.println(new StringReverse().swapWords(str)); } }
方法二:利用JDK提供的方法
public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String[] sArr = str.split(" ");//I love java List<String> list = new ArrayList<String>(); list = Arrays.asList(sArr); // for(int i=0;i<sArr.length;i++){ // list.add(sArr[i]); // } Collections.reverse(list); for(String word:list){ System.out.print(word+" "); } } }
如果描述改一下,输入一个字符串,例如“abcd”,输出"dcba"
public static String reverse(String str){ return new StringBuilder(str).reverse().toString(); }
public void test09() { String str = "hello"; for (int i = str.length() - 1; i >= 0; i--) { char c = str.charAt(i); System.out.print(c); } }