[英]Converting to upper and lower case in Java
我想將字符串的第一個字符轉換為大寫,其余字符轉換為小寫。 我該怎么做?
例:
String inputval="ABCb" OR "a123BC_DET" or "aBcd"
String outputval="Abcb" or "A123bc_det" or "Abcd"
試試這個尺碼:
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()
所有字母都將轉換為Capital, “ABCD”
這是匯入首都的第一封信:
a.substring(0,1).toUpperCase()
這個轉換其他字母簡單
a.substring(1).toLowerCase();
我們可以得到這兩個的總和
a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();
結果= “Abcd”
來自apache commons-lang的 WordUtils.capitalizeFully(str)
具有所需的確切語義。
String inputval="ABCb";
String result = inputval.substring(0,1).toUpperCase() + inputval.substring(1).toLowerCase();
將“ABCb”更改為“Abcb”
我認為這比任何先前的正確答案都簡單。 我也會投入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
長度為1時, s.substring(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 :+*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.