如何使用Java删除字符串中的重复空格? [英] How to remove duplicate white spaces in string using Java?

查看:951
本文介绍了如何使用Java删除字符串中的重复空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java删除字符串中的重复空格(包括制表符,换行符,空格等等)?

How to remove duplicate white spaces (including tabs, newlines, spaces, etc...) in a string using Java?

推荐答案

喜欢这样:

yourString = yourString.replaceAll("\\s+", " ");

例如

System.out.println("lorem  ipsum   dolor \n sit.".replaceAll("\\s+", " "));

输出

lorem ipsum dolor sit.






那是什么 \s + 是什么意思?


What does that \s+ mean?

\s + 是一个正则表达式。 \s 匹配空格,制表符,换行符,回车符,换页符或垂直制表符, + 表示其中一个或多个。因此,上面的代码将折叠所有空格子串长于一个字符,只有一个空格字符。

\s+ is a regular expression. \s matches a space, tab, new line, carriage return, form feed or vertical tab, and + says "one or more of those". Thus the above code will collapse all "whitespace substrings" longer than one character, with a single space character.

来源: Java:删除字符串中的重复空格

这篇关于如何使用Java删除字符串中的重复空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆