描述:给我一个字符串,例如I love java,输出: java love I
方法一
[java] view plaincopyprint?
- 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));
- }
- }
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提供的方法)
[java] view plaincopyprint?
- 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+" ");
- }
- }
- }
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",
当然了方法很多,这里我提供一个jdk自带的方法,比较简单
[java] view plaincopyprint?
- public static String reverse(String str){
- return new StringBuilder(str).reverse().toString();
- }
public static String reverse(String str){ return new StringBuilder(str).reverse().toString(); }
[java] view plaincopyprint?
- @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);
- }
- }
@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); } }
版权声明:感觉我写的还算不错的的话希望你能够动动你的鼠标和键盘为我点上一个赞或是为我奉献上一个评论,在下感激不尽!_______________________________________________________欢迎转载,希望在你转载的同时,添加原文地址,谢谢配合
时间: 2024-10-26 09:37:11