我想将字符串的第一个字符转换为大写,并将其余字符转换为小写。我该怎么做?
例:
String inputval="ABCb" OR "a123BC_DET" or "aBcd"
String outputval="Abcb" or "A123bc_det" or "Abcd"
Answers:
尝试以下尺寸:
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();
}
基本上,它首先处理空字符串和一个字符的特殊情况,否则正确处理一个两个字符以上的字符串。而且,正如评论中指出的那样,功能不需要使用一个字符的特殊情况,但我仍然希望保持明确,特别是如果它导致更少的无用调用(例如子字符串获取空字符串)的情况下,它,然后附加它。
String a = "ABCD"
使用这个
a.toLowerCase();
所有字母都将
使用此格式转换为简单的“ abcd”
a.toUpperCase()
所有字母都将转换为大写字母“ ABCD”
该首字母转换为大写:
a.substring(0,1).toUpperCase()
这个转换其他字母简单
a.substring(1).toLowerCase();
我们可以得到这两个的总和
a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();
结果= “ Abcd”
WordUtils.capitalizeFully(str)来自apache commons-lang的语言具有所需的确切语义。
我认为这比任何先前的正确答案都要简单。我还将抛出javadoc。:-)
/**
* 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.substring(1)在s长度为1时返回空字符串。
/* 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 :+*/