如何从 Java 中的字符串中正确修剪空格? [英] How to properly trim whitespaces from a string in Java?

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

问题描述

JDK 的 String.trim() 方法非常简单,只删除了 ascii 控制字符.

The JDK's String.trim() method is pretty naive, and only removes ascii control characters.

Apache Commons 的 StringUtils.strip() 稍微好一点,但使用 JDK 的 Character.isWhitespace(),其中 不将不间断空格识别为空格.

Apache Commons' StringUtils.strip() is slightly better, but uses the JDK's Character.isWhitespace(), which doesn't recognize non-breaking space as whitespace.

那么在 Java 中修剪字符串的最完整、Unicode 兼容、安全和正确的方法是什么?

So what would be the most complete, Unicode-compatible, safe and proper way to trim a string in Java?

顺便说一句,有没有比 commons-lang 更好的库可以用来处理这类事情?

And incidentally, is there a better library than commons-lang that I should be using for this sort of stuff?

推荐答案

Google 已经制作了 guava-libraries 最近可用.它 可能有您要找的东西:

Google has made guava-libraries available recently. It may have what you are looking for:

CharMatcher.inRange('', ' ').trimFrom(str)

等价于String.trim(),但是你可以自定义要修剪的内容,参考JavaDoc.

is equivalent to String.trim(), but you can customize what to trim, refer to the JavaDoc.

例如,它有 自己定义的WHITESPACE 与JDK不同,是按照最新的Unicode标准定义的,所以你需要的可以写成:

For instance, it has its own definition of WHITESPACE which differs from the JDK and is defined according to the latest Unicode standard, so what you need can be written as:

CharMatcher.WHITESPACE.trimFrom(str)

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

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