简体   繁体   English

如何使字符串的首字母大写和其他小写

[英]How to make String first letter capital and others small

I am trying to convert String first letter as capital and remaining should be small.我正在尝试将字符串的第一个字母转换为大写字母,剩余的应该很小。 I tried below code.我试过下面的代码。 It's working fine with convert first letter capital but it's converting remaining letter as small.它可以很好地转换首字母大写,但它会将剩余的字母转换为小写字母。

String str = "hiGh";
// capitalize first letter
String output = str.substring(0, 1).toUpperCase() + str.substring(1)

Output should be: High Output 应该是: High

You could manipulate the characters of a String to make sure that only the first one is uppercase,您可以操纵String的字符以确保只有第一个是大写的,

String capitalizeFirstOf(String s){
 char[] chars = s.toCharArray();
  for (int i=0; i<s.length(); i++){
   if (i==0){
    chars[i] = Character.toUpperCase(chars[i]);
   }else{
    chars[i] = Character.toLowerCase(chars[i]);
   }
  }

  return new String(chars);
}

You need to change the later substring to the lowercase.需要把后面的substring改成小写。 Use the following code:使用以下代码:

String name  = "hiGH"; 
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();

If your doing much string converting i would recomend using a libary like: apache commons 3如果您进行大量字符串转换,我建议您使用以下库: apache commons 3

They have eg UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize etc.他们有例如UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize等。

So you don't have to put you time on simple string methods.所以你不必把时间花在简单的字符串方法上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在java中使String首字母大写 - Make String first letter capital in java 字符串中最常见的字母(大写和小写) - Most common letter ( Capital and small) in a string 使用字符串模板将第一封信转换为大写 - Convert First Letter to Capital using String Template 正则表达式匹配第一个大写字母,然后是一个或多个小写字母 - Regex matching first capital letter followed by one or more small letters 如何将Java JEditorPane中的小写字母自动更新为大写字母? - How to automatically update small letter characters to capital letter in Java JEditorPane? android中的首字母大写,android中的首字母如何大写? - How to first letter capital in android , How to capitalise first letter in android? 寻找删除边上空格的方法,将所有字母更改为小写,第一个字母为大写字母 - Looking for method to remove spaces on sides, change all letters to small with first letter as capital letter 搜索字符串中的大写字母 - Search for Capital Letter in String 如何使程序计算字符串中以大写字母开头的句子数? - How do I make my program count the number of sentences starting with a capital letter in a string? 如果首字母大写,请删除单词 - Removing words if the first letter is capital
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM