此示例说明如何大写字符串。我们使用WordUtilsApache提供的类中的方法commons-text;。我们可以使用WordUtils.capitalize(str)或WordUtils.capitalizeFully(str)。
让我们看下面的例子:
package org.nhooo.example.commons.text; import org.apache.commons.text.WordUtils; public class WordCapitalize { public static void main(String[] args) { // 将字符串中所有用空格分隔的单词大写, // 每个单词只有第一个字母大写。 String str = WordUtils.capitalize( "The quick brown fox JUMPS OVER the lazy dog."); System.out.println("str = " + str); // 将字符串中所有由空格分隔的单词大写 // 其余字符串为小写。 str = WordUtils.capitalizeFully( "The quick brown fox JUMPS OVER the lazy dog."); System.out.println("str = " + str); } }
这是程序的结果:
str = The Quick Brown Fox JUMPS OVER The Lazy Dog. str = The Quick Brown Fox Jumps Over The Lazy Dog.
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-text/1.7/commons-text-1.7.jar --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.7</version> </dependency>