Java字符串驼峰与下换线格式转换如何实现
下面是自己写的三个方法,直接类名.方法即可调用,注意此处未做异常处理.
1.下划线转驼峰lowerLineToHump()
2.首字母大写capitalizeTheFirstLetter()
3.驼峰转下划线humpToLowerLine()
packageyang.demo.justwrite; importjava.util.regex.Matcher; importjava.util.regex.Pattern; /** *@Description:变量名转换 *@Class:VariableNameConversion *@Author:Yiang37 *@Date:2020/11/315:23 *@Version:1.0 */ publicclassVariableNameConversion{ privatestaticPatternhumpPattern=Pattern.compile("[A-Z]"); publicstaticvoidmain(String[]args){ System.out.println(lowerLineToHump("NAME_AND_addREsS")); System.out.println(capitalizeTheFirstLetter("nAMe")); System.out.println(humpToLowerLine("nameAndAddress")); } /** *@Description:下划线格式->驼峰大小写均可 **NAME_AND_ADDRESS->nameAndAddress *@Author:Yiang37 *@Date:2020/11/0315:26:02 *@Version:1.0 *@method:lowerLineAndUppercaseToHump() *@param:[Big_] *@return:java.lang.String */ publicstaticStringlowerLineToHump(StringlowerLineAndUppercaseStr){ //拆分成数组 String[]eachStr=lowerLineAndUppercaseStr.split("_"); StringBuilderresStr=newStringBuilder(); StringfirstStr=""; StringtempStr=""; for(inti=0;i
首字母大写 *NAME->Name *name->Name *NaMe->Name *@Author:Yiang37 *@Date:2020/11/0316:50:16 *@Version:1.0 *@method:capitalizeTheFirstLetter() *@param:[str] *@return:java.lang.String */ publicstaticStringcapitalizeTheFirstLetter(Stringstr){ charfirstChar=str.toUpperCase().charAt(0); StringnextStr=str.toLowerCase().substring(1); returnfirstChar+nextStr; } /** *@Description:驼峰->下划线格式默认小写,存在第二个形参且为true时大写. *@Author:Yiang37 *@Date:2020/11/0317:10:25 *@Version:1.0 *@method:humpToLowerLine() *@param:[humpStr,UppercaseZeroAndLowercaseOne] *@return:java.lang.String */ publicstaticStringhumpToLowerLine(StringhumpStr,boolean...defaultUppercaseAndTrueLowercase){ Matchermatcher=humpPattern.matcher(humpStr); StringBuffersb=newStringBuffer(); while(matcher.find()){ matcher.appendReplacement(sb,"_"+matcher.group(0).toLowerCase()); } matcher.appendTail(sb); //如果第二个形参为true转为大写 if(defaultUppercaseAndTrueLowercase.length>=1&&defaultUppercaseAndTrueLowercase[0]){ returnsb.toString().toUpperCase(); } returnsb.toString(); } }
输出结果
nameAndAddress
Name
name_and_address
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。