8

Java将英文字符串转换为驼峰式大小写的方法 | baeldung

 3 years ago
source link: https://www.jdon.com/56937
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Java将英文字符串转换为驼峰式大小写的方法 | baeldung

驼峰式大小写有两种类型:

  • 驼峰小写,第一个单词的第一个字符是小写:thisIsLowerCamelCase
  • 驼峰大写,也称为标题大写,其中第一个单词的第一个字符是大写的:ThisIsLowerCamelCase

使用正则:

String[] words = text.split("[\\W_]+");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
    String word = words[i];
    if (i == 0) {
        word = word.isEmpty() ? word : word.toLowerCase();
    } else {
        word = word.isEmpty() ? word : Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase();      
    }
    builder.append(word);
}
return builder.toString();

使用Apache Commons Text,我们需要将它添加到我们的项目中:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

这个库在CaseUtils 中提供了一个toCamelCase方法 :

String camelCase = CaseUtils.toCamelCase(text, false, delimiter);

使用 Guava,让我们将其依赖项添加到我们的项目中:

<dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>28.1-jre</version>
</dependency>

Guava 有一个实用程序类CaseFormat,用于格式转换:

String camelCase = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "THIS_STRING_SHOULD_BE_IN_CAMEL_CASE");

完整的源代码可以在 GitHub 上找到


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK