描述:给我一个字符串,例如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 = ();
swap(arr, 0, - 1);
int begin = 0;
for (int i = 1; i < ; 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";
(new StringReverse().swapWords(str));
}
}
方法二:(利用jdk提供的方法)
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner();
String str = ();
String[] sArr = (" ");//I love java
List<String> list = new ArrayList<String>();
list = (sArr);
// for(int i=0;i<;i++){
// (sArr[i]);
// }
(list);
for(String word:list){
(word+" ");
}
}
}
当然了方法很多,这里我提供一个jdk自带的方法,比较简单
public static String reverse(String str){
return new StringBuilder(str).reverse().toString();
}
@Test
public void test09() {
String str = "hello";
for (int i = () - 1; i >= 0; i--) {
char c = (i);
(c);
}
}