第一种:
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);
}
}
到此这篇关于Java实现字符串反转的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持编程网。