如何在Java中去除字符串中的空格?
在 Java 里,去除字符串中的空格有多种方法,下面为你详细介绍:
1. 使用 replaceAll
方法去除所有空格
replaceAll
方法能依据正则表达式替换字符串里的特定字符。利用 \\s
匹配所有空格(包含空格、制表符、换行符等),并将其替换为空字符串。
public class RemoveSpaces {public static void main(String[] args) {String str = " Hello World! ";String result = str.replaceAll("\\s", "");System.out.println(result); }
}
在上述代码中,str.replaceAll("\\s", "")
把字符串 str
里的所有空格都替换成了空字符串,进而得到去除空格后的字符串。
2. 使用 replace
方法去除所有空格
replace
方法可以直接把字符串里的某个字符或字符序列替换成其他字符或字符序列。若要去除空格,可直接将空格字符替换为空字符串。
public class RemoveSpaces {public static void main(String[] args) {String str = " Hello World! ";String result = str.replace(" ", "");System.out.println(result); }
}
这里的 str.replace(" ", "")
会把字符串 str
中的所有空格字符替换为空字符串。
3. 去除字符串首尾空格
若只需去除字符串首尾的空格,可使用 trim
方法。
public class RemoveSpaces {public static void main(String[] args) {String str = " Hello World! ";String result = str.trim();System.out.println(result); }
}
str.trim()
方法会去除字符串 str
首尾的空格,不过字符串中间的空格不会受影响。
4. 使用 StringBuilder
手动去除空格
通过遍历字符串的每个字符,把非空格字符添加到 StringBuilder
里,最终构建出无空格的字符串。
public class RemoveSpaces {public static String removeAllSpaces(String str) {StringBuilder sb = new StringBuilder();for (int i = 0; i < str.length(); i++) {if (str.charAt(i) != ' ') {sb.append(str.charAt(i));}}return sb.toString();}public static void main(String[] args) {String str = " Hello World! ";String result = removeAllSpaces(str);System.out.println(result); }
}
在 removeAllSpaces
方法中,借助 StringBuilder
遍历字符串,只添加非空格字符,最后将 StringBuilder
转换为字符串返回。