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 replacedStr = str.replace(" ", "_");
System.out.println("使用 replace() 方法: '" + replacedStr + "'");
}
}
\\s+ 匹配一个或多个空白字符(包括空格、制表符等),并将其替换为空字符串,从而去除所有空格。上一篇:java数据结构与算法
下一篇:java获取当前服务器ip
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站