去空格方法
- str.trim(); //去掉首尾空格
- str.replace(" ",""); //去除所有空格,包括首尾、中间
反转方法
1. 利用 StringBuffer 或 StringBuilder 的 reverse 成员方法:
// StringBuffer
public static String reverse1(String str) {
return new StringBuilder(str).reverse().toString();
}
2. 利用 String 的 toCharArray 方法先将字符串转化为 char 类型数组,然后将各个字符进行重新拼接:
// toCharArray
public static String reverse2(String str) {
char[] chars = str.toCharArray();
String reverse = "";
for (int i = chars.length - 1; i >= 0; i--) {
reverse += chars[i];
}
return reverse;
}
3. 利用 String 的 CharAt 方法取出字符串中的各个字符:
// charAt
public static String reverse3(String str) {
String reverse = "";
int length = str.length();
for (int i = 0; i < length; i++) {
reverse = str.charAt(i) + reverse;
}
return reverse;
}
实现:
public class Test {
public static void main(String[] args) {
String str= " ab cd ";
System.out.println(reverseString(str));
}
public static String reverseString(String str) {
//去空格
String s = str.replace(" ", "");
//反转
return new StringBuilder(s).reverse().toString();
}
}