我正在使用 Java 从用户那里获取 String
输入。我正在尝试将此输入的第一个字母大写。
我试过这个:
String name;
BufferedReader br = new InputStreamReader(System.in);
String s1 = name.charAt(0).toUppercase());
System.out.println(s1 + name.substring(1));
这导致了这些编译器错误:
类型不匹配:无法从 InputStreamReader 转换为 BufferedReader
无法在原始类型 char 上调用 toUppercase()
String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = "Java"
用你的例子:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Actually use the Reader
String name = br.readLine();
// Don't mistake String object with a Character object
String s1 = name.substring(0, 1).toUpperCase();
String nameCapitalized = s1 + name.substring(1);
System.out.println(nameCapitalized);
}
StringUtils.capitalize(..)
来自 commons-lang
StringUtils.capitalize( "fred from jupiter" );
产生 "Fred from jupiter"
。容易... :D
将字符串的第一个字母大写的更短/更快的版本代码是:
String name = "stackoverflow";
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
name
的值为 "Stackoverflow"
使用 Apache 的公共库。将您的大脑从这些东西中解放出来,避免空指针和索引越界异常
步骤1:
通过将其放入 build.gradle
依赖项来导入 apache 的通用语言库
compile 'org.apache.commons:commons-lang3:3.6'
第2步:
如果你确定你的字符串都是小写的,或者你只需要初始化第一个字母,直接调用
StringUtils.capitalize(yourString);
如果您想确保只有第一个字母大写,例如对 enum
执行此操作,请先调用 toLowerCase()
,并记住如果输入字符串为空,它将抛出 NullPointerException
。
StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());
以下是 apache 提供的更多示例。这是免费的
StringUtils.capitalize(null) = null
StringUtils.capitalize("") = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
笔记:
WordUtils
也包含在此库中,但已弃用。请不要使用它。
爪哇:
只是一个用于大写每个字符串的辅助方法。
public static String capitalize(String str)
{
if(str == null || str.length()<=1) return str;
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
之后只需调用 str = capitalize(str)
科特林:
str.capitalize()
如果您使用弹簧:
import static org.springframework.util.StringUtils.capitalize;
...
return capitalize(name);
实施: org/springframework/util/StringUtils.java#L535-L555
参考: javadoc-api/org/springframework/util/StringUtils.html#capitalize
注意:如果您已经有 Apache Common Lang 依赖项,那么请考虑使用他们的 StringUtils.capitalize 作为其他答案的建议。
你想要做的可能是这样的:
s1 = name.substring(0, 1).toUpperCase() + name.substring(1);
(将第一个字符转换为大写并添加原始字符串的其余部分)
此外,您创建了一个输入流阅读器,但从不读取任何行。因此 name
将始终为 null
。
这应该有效:
BufferedReader br = new InputstreamReader(System.in);
String name = br.readLine();
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1);
WordUtils.capitalize(java.lang.String)
来自 Apache Commons。
以下解决方案将起作用。
String A = "stackOverflow";
String ACaps = A.toUpperCase().charAt(0)+A.substring(1,A.length());
//Will print StackOverflow
您不能在原始 char 上使用 toUpperCase() ,但您可以先将整个字符串设为大写,然后取第一个字符,然后附加到子字符串,如上所示。
使用此实用方法获取所有首字母大写。
String captializeAllFirstLetter(String name)
{
char[] array = name.toCharArray();
array[0] = Character.toUpperCase(array[0]);
for (int i = 1; i < array.length; i++) {
if (Character.isWhitespace(array[i - 1])) {
array[i] = Character.toUpperCase(array[i]);
}
}
return new String(array);
}
将字符串设置为小写,然后将第一个字母设置为大写,如下所示:
userName = userName.toLowerCase();
然后将第一个字母大写:
userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();
substring 只是得到一个更大的字符串,然后我们将它们组合在一起。
String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);
它将工作 101%
public class UpperCase {
public static void main(String [] args) {
String name;
System.out.print("INPUT: ");
Scanner scan = new Scanner(System.in);
name = scan.next();
String upperCase = name.substring(0, 1).toUpperCase() + name.substring(1);
System.out.println("OUTPUT: " + upperCase);
}
}
这是我关于所有可能选项的主题的详细文章Capitalize First Letter of String in Android
Java中字符串首字母大写的方法
public static String capitalizeString(String str) {
String retStr = str;
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
}catch (Exception e){}
return retStr;
}
KOTLIN 中字符串首字母大写的方法
fun capitalizeString(str: String): String {
var retStr = str
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
} catch (e: Exception) {
}
return retStr
}
也是最短的:
String message = "my message";
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message) // Will output: My message
为我工作。
在 Android Studio 中
将此依赖项添加到您的 build.gradle (Module: app)
dependencies {
...
compile 'org.apache.commons:commons-lang3:3.1'
...
}
现在你可以使用
String string = "STRING WITH ALL CAPPS AND SPACES";
string = string.toLowerCase(); // Make all lowercase if you have caps
someTextView.setText(WordUtils.capitalize(string));
WordUtils.capitalizeFully() 呢?
import org.apache.commons.lang3.text.WordUtils;
public class Main {
public static void main(String[] args) {
final String str1 = "HELLO WORLD";
System.out.println(capitalizeFirstLetter(str1)); // output: Hello World
final String str2 = "Hello WORLD";
System.out.println(capitalizeFirstLetter(str2)); // output: Hello World
final String str3 = "hello world";
System.out.println(capitalizeFirstLetter(str3)); // output: Hello World
final String str4 = "heLLo wORld";
System.out.println(capitalizeFirstLetter(str4)); // output: Hello World
}
private static String capitalizeFirstLetter(String str) {
return WordUtils.capitalizeFully(str);
}
}
你也可以试试这个:
String s1 = br.readLine();
char[] chars = s1.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
s1= new String(chars);
System.out.println(s1);
这比使用子字符串更好(优化)。 (但不要担心小字符串)
您可以使用 substring()
来执行此操作。
但是有两种不同的情况:
情况1
如果您大写的 String
是为了便于阅读,您还应该指定默认语言环境:
String firstLetterCapitalized =
myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);
案例2
如果您大写的 String
是机器可读的,请避免使用 Locale.getDefault()
,因为返回的字符串在不同区域之间会不一致,在这种情况下,请始终指定相同的语言环境(例如,toUpperCase(Locale.ENGLISH)
)。这将确保您用于内部处理的字符串是一致的,这将帮助您避免难以发现的错误。
注意:您不必为 toLowerCase()
指定 Locale.getDefault()
,因为这是自动完成的。
要获得首字母大写和其他小写字母,您可以使用以下代码。我已经通过子字符串函数完成了。
String currentGender="mAlE";
currentGender=currentGender.substring(0,1).toUpperCase()+currentGender.substring(1).toLowerCase();
这里 substring(0,1).toUpperCase() 将第一个字母大写,而 substring(1).toLowercase() 将所有剩余的字母转换为小写。
输出:
男性
试试这个
这个方法的作用是,考虑“hello world”这个词,这个方法把它变成“Hello World”,每个词的开头都大写。
private String capitalizer(String word){
String[] words = word.split(" ");
StringBuilder sb = new StringBuilder();
if (words[0].length() > 0) {
sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
}
}
return sb.toString();
}
现有的答案是
不正确:他们认为 char 是一个单独的字符(代码点),而它是一个 UTF-16 单词,可以是代理对的一半,或者
使用本身还不错但需要向项目添加依赖项的库,或者
使用完全有效但并非总是可行的 Java 8 Streams。
让我们看一下 surrogate characters(每个这样的字符都由两个 UTF-16 单词组成 - Java char
)并且可以有大写和小写变体:
IntStream.rangeClosed(0x01_0000, 0x10_FFFF)
.filter(ch -> Character.toUpperCase(ch) != Character.toLowerCase(ch))
.forEach(ch -> System.out.print(new String(new int[] { ch }, 0, 1)));
它们中的许多可能看起来像“豆腐”(□),但它们大多是稀有脚本的有效字符,并且某些字体支持它们。
例如,让我们看一下 Deseret Small Letter Long I (𐐨), U+10428, "\uD801\uDC28"
:
System.out.println("U+" + Integer.toHexString(
"\uD801\uDC28".codePointAt(0)
)); // U+10428
System.out.println("U+" + Integer.toHexString(
Character.toTitleCase("\uD801\uDC28".codePointAt(0))
)); // U+10400 — ok! capitalized character is another code point
System.out.println("U+" + Integer.toHexString(new String(new char[] {
Character.toTitleCase("\uD801\uDC28".charAt(0)), "\uD801\uDC28".charAt(1)
}).codePointAt(0))); // U+10428 — oops! — cannot capitalize an unpaired surrogate
因此,即使在 char
不能大写的情况下,代码点也可以大写。考虑到这一点,让我们编写一个正确的(并且兼容 Java 1.5!)大写字母:
@Contract("null -> null")
public static CharSequence capitalize(CharSequence input) {
int length;
if (input == null || (length = input.length()) == 0) return input;
return new StringBuilder(length)
.appendCodePoint(Character.toTitleCase(Character.codePointAt(input, 0)))
.append(input, Character.offsetByCodePoints(input, 0, 1), length);
}
并检查它是否有效:
public static void main(String[] args) {
// ASCII
System.out.println(capitalize("whatever")); // w -> W
// UTF-16, no surrogate
System.out.println(capitalize("что-то")); // ч -> Ч
// UTF-16 with surrogate pairs
System.out.println(capitalize("\uD801\uDC28")); // 𐐨 -> 𐐀
}
也可以看看:
代理对 Java 中的“代理对”是什么?
大写与标题大小写 https://stackoverflow.com/a/47887432/3050249
当前的答案要么不正确,要么使这个简单的任务过于复杂。在进行了一些研究之后,以下是我提出的 two approaches:
<强> 1。字符串的 substring()
方法
public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
例子:
System.out.println(capitalize("java")); // Java
System.out.println(capitalize("beTa")); // BeTa
System.out.println(capitalize(null)); // null
2. Apache Commons 朗
Apache Commons Lang 库为此目的提供 StringUtils
类:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
不要忘记将以下依赖项添加到您的 pom.xml
文件中:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
StringUtils.capitalize("a")
进行另一个测试。
简单的解决方案!不需要任何外部库,它可以处理空字符串或一个字母字符串。
private String capitalizeFirstLetter(@NonNull String str){
return str.length() == 0 ? str
: str.length() == 1 ? str.toUpperCase()
: str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
这只是为了告诉你,你并没有那么错。
BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine();
//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());
System.out.println(s1+name.substring(1));
注意: 这根本不是最好的方法。这只是为了向 OP 展示它也可以使用 charAt()
来完成。 ;)
Character.toString(name.charAt(0))
而不是 ""+name.charAt(0)
来展示我真正想做的事情。
这将起作用
char[] array = value.toCharArray();
array[0] = Character.toUpperCase(array[0]);
String result = new String(array);
您可以使用以下代码:
public static void main(String[] args) {
capitalizeFirstLetter("java");
capitalizeFirstLetter("java developer");
}
public static void capitalizeFirstLetter(String text) {
StringBuilder str = new StringBuilder();
String[] tokens = text.split("\\s");// Can be space,comma or hyphen
for (String token : tokens) {
str.append(Character.toUpperCase(token.charAt(0))).append(token.substring(1)).append(" ");
}
str.toString().trim(); // Trim trailing space
System.out.println(str);
}
如果输入是大写,则使用以下:
str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
如果输入是小写,则使用以下:
str.substring(0, 1).toUpperCase() + str.substring(1);
使用 commons.lang.StringUtils
的最佳答案是:
public static String capitalize(String str) {
int strLen;
return str != null && (strLen = str.length()) != 0 ? (new StringBuffer(strLen)).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1)).toString() : str;
}
我觉得它很棒,因为它用 StringBuffer 包装了字符串。您可以根据需要操作 StringBuffer,尽管使用相同的实例。
不定期副业成功案例分享
str.substring(0, 1)
可能会返回无效的 unicode 字符串 - stackoverflow.com/questions/70178612/…