Java 使用 StringBuiffer 将多个空格替换为单个空格
StringBuiffer
还可以从不均匀间隔的字符串中获取字符串。
String siteName = "on it road world . com"; StringTokenizer st = new StringTokenizer(siteName, " "); StringBuffer sb = new StringBuffer(); while(st.hasMoreElements()) { sb.append(st.nextElement()).append(" "); } String nameWithProperSpacing = sb.toString(); System.out.println( nameWithProperSpacing ); // 删除前后的空格 nameWithProperSpacing = nameWithProperSpacing.trim(); System.out.println( nameWithProperSpacing );
使用 StringUtils 去除字符串中多余的空格
Maven 依赖
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.7</version> </dependency>
去除单词之间的空格示例
String siteName = "on it road world . com"; String nameWithProperSpacing = StringUtils.normalizeSpace( siteName ); System.out.println( nameWithProperSpacing );
输出:
on it road world . com
www. On IT Road .com
Java用正则表达式去除单词之间多余的空格
使用正则表达式,把 2 个或者多个空格替换为单个空格。
我们使用正则表达式模式 "\s+" 。
\\s
匹配空格、制表符、换行符、回车符、换页符或者垂直制表符。+
表示出现一次或者多次。
String siteName = "on it road world . com"; String nameWithProperSpacing = siteName.replaceAll("\s+", " "); // 删除前后空格 nameWithProperSpacing = nameWithProperSpacing.trim(); System.out.println( nameWithProperSpacing );
日期:2020-09-17 00:10:09 来源:oir作者:oir