java WordUtils.capitalize 的替代品?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44599940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alternatives for WordUtils.capitalize?
提问by KevinO
I'm trying to capitalize every word in a string using WordUtils.capitalize(String)
because it does exactly what I wanted. However it is now deprecated.
我正在尝试将字符串中的每个单词都大写,WordUtils.capitalize(String)
因为它完全符合我的要求。然而,它现在已被弃用。
What method should I use instead? Or do I have to write my own method?
我应该使用什么方法?还是我必须编写自己的方法?
回答by KevinO
The implementation in commons-lang3
is deprecated. However, the same method is implemented in commons-text
. Therefore, you may use essentially the same method, but will need to add a new .jar file and adjust the import statement.
中的实现commons-lang3
已弃用。但是,在commons-text
. 因此,您可以使用本质上相同的方法,但需要添加一个新的 .jar 文件并调整导入语句。
From the javadoc of org.apache.commons.lang3.text.WordUtils
:
来自 的javadocorg.apache.commons.lang3.text.WordUtils
:
as of 3.6, use commons-text WordUtils instead
从 3.6 开始,改用 commons-text WordUtils
If using Maven (or similar), add the following:
如果使用 Maven(或类似的),请添加以下内容:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.1</version>
</dependency>
The reference for Commons Text: Apache Commons Text is a library focused on algorithms working on strings.
Commons Text 的参考:Apache Commons Text 是一个专注于处理字符串的算法的库。
回答by cн?dk
You can use apache.commons's StringUtils.capitalise():
您可以使用apache.commons的StringUtils.capitalise():
public static String capitalize(String str)
Capitalizes a String changing the first character to title case as per Character.toTitleCase(int). No other characters are changed.
公共静态字符串大写(字符串 str)
根据 Character.toTitleCase(int) 将第一个字符更改为标题大小写的字符串大写。没有改变其他字符。
Instead of WordUtils
class use StringUtils
from the same package, so you don't have to change your project configuration by adding extra jars.
而不是从同一个包中WordUtils
使用类StringUtils
,因此您不必通过添加额外的 jar 来更改项目配置。
Alternative:
选择:
Or you can implement it yourself, you can try something like this:
或者你可以自己实现它,你可以尝试这样的事情:
String str = "john";
String newStr = str.substring(0, 1).toUpperCase() + str.substring(1);
Will print John
.
将打印John
。