描述:给我一个字符串,例如I love java,输出: java love I
方法一
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+" ");
}
}
}
当然了方法很多,这里我提供一个jdk自带的方法,比较简单
public static String reverse(String str){
return new StringBuilder(str).reverse().toString();
}
@Test
public void test09() {
String str = "hello";
for (int i = str.length() - 1; i >= 0; i--) {
char c = str.charAt(i);
System.out.print(c);
}
}