欢迎光临
感受代码之美

Java中将字符串转为驼峰格式

方式1

使用CaseUtils 对Java字符串进行转换为驼峰格式:

 CaseUtils.toCamelCase(null, false)                                 = null
 CaseUtils.toCamelCase("", false, *)                                = ""
 CaseUtils.toCamelCase(*, false, null)                              = *
 CaseUtils.toCamelCase(*, true, new char[0])                        = *
 CaseUtils.toCamelCase("To.Camel.Case", false, new char[]{'.'})     = "toCamelCase"
 CaseUtils.toCamelCase(" to @ Camel case", true, new char[]{'@'})   = "ToCamelCase"
 CaseUtils.toCamelCase(" @to @ Camel case", false, new char[]{'@'}) = "toCamelCase"

构造方法:

public static String toCamelCase(String str,
                                 boolean capitalizeFirstLetter,
                                 char... delimiters)

其中:str为要转换的字符串;capitalizeFirstLetter表示是否首字母大写;delimiters指定连词符。

maven依赖:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-text -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.8</version>
</dependency>

方式2

使用Google Guavacom.google.common.base.CaseFormat

引入依赖:

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.0</version>
</dependency>

使用:

CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, string_to_format)
赞(1)
未经允许禁止转载:四个空格 » Java中将字符串转为驼峰格式

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址