Java實作的三種字串反轉
第一種:
public class Main { public static void main(String[] args) { String s1 = "asdfghjkl"; System.out.println(new StringBuilder(s1).reverse().toString()); } }
第二種:
public class Main { public static void main(String[] args) { String s1 = "asdfghjkl"; String[] s = s1.split(""); List<String> list = list = Arrays.asList(s); Collections.reverse(list); System.out.println(list); } }
第三種:
public class Main { public static void main(String[] args) { String s1 = "asdfghjkl"; System.out.println(new Main().swapWords(s1)); } 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--; } } 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); } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/168191.html
標籤:Java
上一篇:別再重復造輪子了,幾個值得應用到專案中的 Java 開源庫送給你
下一篇:小白求指教
