在 Java 中转换为大小写

我想将字符串的第一个字符转换为大写,其余字符转换为小写。我该怎么做?

例如:

String inputval="ABCb" OR "a123BC_DET" or "aBcd"
String outputval="Abcb" or "A123bc_det" or "Abcd"
351476 次浏览
String inputval="ABCb";
String result = inputval.substring(0,1).toUpperCase() + inputval.substring(1).toLowerCase();

将“ ABCb”改为“ ABCb”

Apache commons-lang中的 WordUtils.capitalizeFully(str)具有所需的精确语义。

试试这个大小:

String properCase (String inputVal) {
// Empty strings should be returned as-is.


if (inputVal.length() == 0) return "";


// Strings with only one character uppercased.


if (inputVal.length() == 1) return inputVal.toUpperCase();


// Otherwise uppercase first letter, lowercase the rest.


return inputVal.substring(0,1).toUpperCase()
+ inputVal.substring(1).toLowerCase();
}

它基本上首先处理空字符串和一个字符串的特殊情况,然后正确处理两个加字符的字符串。而且,正如注释中指出的,功能并不需要一个字符的特殊情况,但我仍然喜欢明确的,特别是如果它导致更少的无用调用,例如子字符串得到一个空字符串,小写它,然后追加它。

/* This code is just for convert a single uppercase character to lowercase
character & vice versa.................*/


/* This code is made without java library function, and also uses run time input...*/






import java.util.Scanner;


class CaseConvert {
char c;
void input(){
//@SuppressWarnings("resource")  //only eclipse users..
Scanner in =new Scanner(System.in);  //for Run time input
System.out.print("\n Enter Any Character :");
c=in.next().charAt(0);     // input a single character
}
void convert(){
if(c>=65 && c<=90){
c=(char) (c+32);
System.out.print("Converted to Lowercase :"+c);
}
else if(c>=97&&c<=122){
c=(char) (c-32);
System.out.print("Converted to Uppercase :"+c);
}
else
System.out.println("invalid Character Entered  :" +c);


}




public static void main(String[] args) {
// TODO Auto-generated method stub
CaseConvert obj=new CaseConvert();
obj.input();
obj.convert();
}


}






/*OUTPUT..Enter Any Character :A Converted to Lowercase :a
Enter Any Character :a Converted to Uppercase :A
Enter Any Character :+invalid Character Entered  :+*/

我认为这比以前的任何正确答案都要简单

/**
* Converts the given string to title case, where the first
* letter is capitalized and the rest of the string is in
* lower case.
*
* @param s a string with unknown capitalization
* @return a title-case version of the string
*/
public static String toTitleCase(String s)
{
if (s.isEmpty())
{
return s;
}
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

长度为1的字符串不需要作为特殊情况处理,因为当 s的长度为1时,s.substring(1)返回空字符串。

String a = "ABCD"

用这个

a.toLowerCase();

所有的字母都会转换成简单的 “ d”
用这个

a.toUpperCase()

所有字母将转换为大写, “ ABCD”

第一个大写字母:

a.substring(0,1).toUpperCase()

这个转换其他字母简单

a.substring(1).toLowerCase();

我们可以得到这两者的总和

a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();

结果 = “ Abcd”