在Java中转换为大写和小写
我想将字符串的第一个字符转换为大写,其余字符转换为小写。我怎么做 例如:在Java中转换为大写和小写,java,string,Java,String,我想将字符串的第一个字符转换为大写,其余字符转换为小写。我怎么做 例如: String inputval="ABCb" OR "a123BC_DET" or "aBcd" String outputval="Abcb" or "A123bc_det" or "Abcd" 将“ABCb”更改为“ABCb”WordUtils。大写(str)from具有所需的精确语义。请尝试此尺寸: String properCase (String inputVal) { // Empty strings
String inputval="ABCb" OR "a123BC_DET" or "aBcd"
String outputval="Abcb" or "A123bc_det" or "Abcd"
将“ABCb”更改为“ABCb”
WordUtils。大写(str)
from具有所需的精确语义。请尝试此尺寸:
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 :+*/
字符,反之亦然*/
/*这段代码没有java库函数,也使用运行时输入*/
导入java.util.Scanner;
类案例转换{
字符c;
无效输入(){
//@SuppressWarnings(“资源”)//仅限eclipse用户。。
Scanner in=new Scanner(System.in);//用于运行时输入
System.out.print(“\n输入任何字符:”);
c=in.next().charAt(0);//输入单个字符
}
void convert(){
如果(c>=65 & & c=97 & & c> p>我认为这比任何先前正确的答案都要简单。
长度为1的字符串不需要作为特例处理,因为s.substring(1)
在s
的长度为1时返回空字符串
String a = "ABCD"
用这个
a.toLowerCase();
a.toUpperCase()
所有字母将转换为简单的,“abcd”
用这个
a.toLowerCase();
a.toUpperCase()
所有字母都将转换为大写,“ABCD”
这是大写的第一个字母:
a.substring(0,1).toUpperCase()
这封信很简单
a.substring(1).toLowerCase();
我们可以得到这两个的总和
a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();
结果=“Abcd”如果inputval为0或1长度,请不要忘记处理。这是一个不必要的情况。请看我的答案。@espertus,你应该在要求别人看答案之前发布你的答案,否则你可能会让他们发疯:-)对不起,@paxdiablo。谢谢你的微笑。:-)你的意思是说比等着看一个拥有200 ti的人的表现更疯狂吗当s.length为1时,Paxdiablo的版本避免了不必要的连接。该版本的代码行数较少,但是否“更简单”仍有争议.一般来说,更简洁并不意味着更可读。性能…很难说,尤其是因为它取决于一个字符串的概率。@StephenC很公平。