public class RemoveSpaces {
public static void main(String[] args) {
// 定义一个包含空格的字符串
String str = " Hello World ";
// 使用 trim() 方法去除字符串两端的空格
String trimmedStr = str.trim();
System.out.println("使用 trim() 方法: '" + trimmedStr + "'");
// 使用 replaceAll() 方法去除所有空格(包括中间的空格)
String noSpacesStr = str.replaceAll("\\s+", "");
System.out.println("使用 replaceAll() 方法: '" + noSpacesStr + "'");
// 使用 replace() 方法去除所有空格(包括中间的空格)
String noSpacesStr2 = str.replace(" ", "");
System.out.println("使用 replace() 方法: '" + noSpacesStr2 + "'");
}
}
\\s+ 匹配一个或多个空白字符(包括空格、制表符等),并将它们替换为空字符串,从而去除所有空格。" " 替换为空字符串 "",从而去除所有空格。通过这些方法,你可以根据实际需求选择合适的方式来去除字符串中的空格。
上一篇:java %运算
下一篇:在线java编辑器
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站