Java中如何将字符串的首字母大写?

发布于 2024-09-27 06:22:08 字数 452 浏览 7 评论 0原文

我正在使用 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()

I am using Java to get a String input from the user. I am trying to make the first letter of this input capitalized.

I tried this:

String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));

which led to these compiler errors:

  • Type mismatch: cannot convert from InputStreamReader to BufferedReader

  • Cannot invoke toUppercase() on the primitive type char

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

三寸金莲 2024-10-04 06:22:08
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);
}
String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = "Java"

With your example:

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);
}
幽梦紫曦~ 2024-10-04 06:22:08

将字符串的第一个字母大写的更短/更快的版本代码是:

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

name 的值是 "Stackoverflow"

The shorter/faster version code to capitalize the first letter of a String is:

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

the value of name is "Stackoverflow"

天气好吗我好吗 2024-10-04 06:22:08

使用 Apache 的公共库。将你的大脑从这些东西中解放出来,避免空指针和空指针。索引越界异常

第 1 步:

通过将其放入 build.gradle 依赖项中来导入 apache 的通用语言库

implementation 'org.apache.commons:commons-lang3:3.6'

第 2 步:

如果您确定你的字符串全部是小写,或者你只需​​要初始化第一个字母,直接调用

StringUtils.capitalize(yourString);

如果你想确保只有第一个字母大写,就像对enum这样做,调用< code>toLowerCase() 首先,请记住,如果输入字符串为 null,它将抛出 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 也包含在此库中,但已弃用。请不要使用它。

Use Apache's common library. Free your brain from these stuffs and avoid Null Pointer & Index Out Of Bound Exceptions

Step 1:

Import apache's common lang library by putting this in build.gradle dependencies

implementation 'org.apache.commons:commons-lang3:3.6'

Step 2:

If you are sure that your string is all lower case, or all you need is to initialize the first letter, directly call

StringUtils.capitalize(yourString);

If you want to make sure that only the first letter is capitalized, like doing this for an enum, call toLowerCase() first and keep in mind that it will throw NullPointerException if the input string is null.

StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());

Here are more samples provided by apache. it's exception free

StringUtils.capitalize(null)  = null
StringUtils.capitalize("")    = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"

Note:

WordUtils is also included in this library, but is deprecated. Please do not use that.

风筝在阴天搁浅。 2024-10-04 06:22:08

如果您使用SPRING

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 作为其他答案表明。

if you use SPRING:

import static org.springframework.util.StringUtils.capitalize;
...


    return capitalize(name);

IMPLEMENTATION: org/springframework/util/StringUtils.java#L535-L555

REF: javadoc-api/org/springframework/util/StringUtils.html#capitalize


NOTE: If you already have Apache Common Lang dependency, then consider using their StringUtils.capitalize as other answers suggest.

空城旧梦 2024-10-04 06:22:08

Java:

只是一个用于将每个字符串大写的辅助方法。

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)


Kotlin:

str.capitalize()

Java:

simply a helper method for capitalizing every string.

public static String capitalize(String str)
{
    if(str == null || str.length()<=1) return str;
    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

After that simply call str = capitalize(str)


Kotlin:

str.capitalize()
喜你已久 2024-10-04 06:22:08

您想要做的可能是这样的:(

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);

What you want to do is probably this:

s1 = name.substring(0, 1).toUpperCase() + name.substring(1);

(converts first char to uppercase and adds the remainder of the original string)

Also, you create an input stream reader, but never read any line. Thus name will always be null.

This should work:

BufferedReader br = new InputstreamReader(System.in);
String name = br.readLine();
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1);
已下线请稍等 2024-10-04 06:22:08

下面的解决方案将起作用。

String A = "stackOverflow";
String ACaps = A.toUpperCase().charAt(0)+A.substring(1,A.length());
//Will print StackOverflow

您不能在原始 char 上使用 toUpperCase() ,但您可以先将整个 String 转换为大写,然后取出第一个字符,然后附加到子字符串,如上所示。

Below solution will work.

String A = "stackOverflow";
String ACaps = A.toUpperCase().charAt(0)+A.substring(1,A.length());
//Will print StackOverflow

You can't use toUpperCase() on primitive char , but you can make entire String to Uppercase first then take the first char, then to append to the substring as shown above.

习ぎ惯性依靠 2024-10-04 06:22:08

使用此实用方法将每个单词的第一个字母大写。

String capitalizeAllFirstLetters(String name) 
{
    char[] array = name.toLowerCase().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);
}

Use this utility method to capitalize the first letter of every word.

String capitalizeAllFirstLetters(String name) 
{
    char[] array = name.toLowerCase().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);
}
苦行僧 2024-10-04 06:22:08

将字符串设置为小写,然后将第一个字母设置为大写,如下所示:

userName = userName.toLowerCase();

然后将第一个字母大写:

userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();

子字符串只是获取较大字符串的一部分,然后我们将它们组合在一起。

Set the string to lower case, then set the first Letter to upper like this:

userName = userName.toLowerCase();

then to capitalise the first letter:

userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();

substring is just getting a piece of a larger string, then we are combining them back together.

清醇 2024-10-04 06:22:08
String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);
String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);
以为你会在 2024-10-04 06:22:08

也是最短的:

String message = "my message";    
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message)    // Will output: My message

为我工作。

Shortest too:

String message = "my message";    
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message)    // Will output: My message

Worked for me.

这是我关于所有可能选项的主题的详细文章 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
}

Here is my detailed article on the topic for all possible options Capitalize First Letter of String in Android

Method to Capitalize First Letter of String in 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;
}

Method to Capitalize First Letter of String in 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
}
熊抱啵儿 2024-10-04 06:22:08

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); 

    }

}

IT WILL WORK 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); 

    }

}
琉璃梦幻 2024-10-04 06:22:08

在 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));

In Android Studio

Add this dependency to your build.gradle (Module: app)

dependencies {
    ...
    compile 'org.apache.commons:commons-lang3:3.1'
    ...
}

Now you can use

String string = "STRING WITH ALL CAPPS AND SPACES";

string = string.toLowerCase(); // Make all lowercase if you have caps

someTextView.setText(WordUtils.capitalize(string));
凉城 2024-10-04 06:22:08

怎么样 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);
    }
}

What about 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);
    }
}
痴者 2024-10-04 06:22:08

简单的解决方案!不需要任何外部库,它可以处理空字符串或一个字母字符串。

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();
}

Simple solution! doesn't require any external library, it can handle empty or one letter string.

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();
}
心欲静而疯不止 2024-10-04 06:22:08

您也可以尝试这个:

String s1 = br.readLine();
char[] chars = s1.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
s1= new String(chars);
System.out.println(s1);

这比使用子字符串更好(优化)。 (但不用担心小绳子)

You can also try this:

String s1 = br.readLine();
char[] chars = s1.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
s1= new String(chars);
System.out.println(s1);

This is better (optimized) than with using substring. (but not to worry on small string)

伴随着你 2024-10-04 06:22:08

您可以使用 substring() 来执行此操作。

但有两种不同的情况:

情况 1

如果您要大写的字符串是为了便于人类阅读,您还应该指定默认区域设置:

String firstLetterCapitalized = 
    myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);

情况 2

如果您要大写的String 是为了机器可读,请避免使用Locale.getDefault(),因为返回的字符串在不同的环境中会不一致。区域,并且在这种情况下始终指定相同的区域设置(例如,toUpperCase(Locale.ENGLISH))。这将确保您用于内部处理的字符串是一致的,这将帮助您避免难以发现的错误。

注意:您不必为 toLowerCase() 指定 Locale.getDefault(),因为这是自动完成的。

You can use substring() to do this.

But there are two different cases:

Case 1

If the String you are capitalizing is meant to be human-readable, you should also specify the default locale:

String firstLetterCapitalized = 
    myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);

Case 2

If the String you are capitalizing is meant to be machine-readable, avoid using Locale.getDefault() because the string that is returned will be inconsistent across different regions, and in this case always specify the same locale (for example, toUpperCase(Locale.ENGLISH)). This will ensure that the strings you are using for internal processing are consistent, which will help you avoid difficult-to-find bugs.

Note: You do not have to specify Locale.getDefault() for toLowerCase(), as this is done automatically.

夏末 2024-10-04 06:22:08

如果输入是 UpperCase ,则使用以下内容:

str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();

如果输入为 LowerCase ,则使用以下内容:

str.substring(0, 1).toUpperCase() + str.substring(1);

If Input is UpperCase ,then Use following :

str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();

If Input is LowerCase ,then Use following :

str.substring(0, 1).toUpperCase() + str.substring(1);

吲‖鸣 2024-10-04 06:22:08

现有的答案要么

  • 不正确:他们认为 char 是一个单独的字符(代码点),而它是一个 UTF-16 单词,可以是代理对的一半,或者
  • 使用不正确的库本身不好,但需要向您的项目添加依赖项,或者
  • 使用 Java 8 Streams 这是完全有效的,但并不总是可行。

让我们看一下代理字符(每个这样的字符由两个UTF-16 单词 — Java chars),并且可以有大写和小写变体:

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 (

Existing answers are either

  • incorrect: they think that char is a separate character (code point), while it is a UTF-16 word which can be a half of a surrogate pair, or
  • use libraries which is not bad itself but requires adding dependencies to your project, or
  • use Java 8 Streams which is perfectly valid but not always possible.

Let's look at surrogate characters (every such character consist of two UTF-16 words — Java chars) and can have upper and lowercase variants:

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)));

Many of them may look like 'tofu' (□) for you but they are mostly valid characters of rare scripts and some typefaces support them.

For example, let's look at 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

So, a code point can be capitalized even in cases when char cannot be.
Considering this, let's write a correct (and Java 1.5 compatible!) capitalizer:

@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);
}

And check whether it works:

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")); // ???? -> ????
}

See also:

深陷 2024-10-04 06:22:08

当前的答案要么不正确,要么使这个简单的任务过于复杂。经过一些研究后,我提出了两种方法与:

1。 String 的 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 Lang

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>

Current answers are either incorrect or over-complicate this simple task. After doing some research, here are two approaches I come up with:

1. String's substring() Method

public static String capitalize(String str) {
    if(str== null || str.isEmpty()) {
        return str;
    }

    return str.substring(0, 1).toUpperCase() + str.substring(1);
}

Examples:

System.out.println(capitalize("java")); // Java
System.out.println(capitalize("beTa")); // BeTa
System.out.println(capitalize(null)); // null

2. Apache Commons Lang

The Apache Commons Lang library provides StringUtils the class for this purpose:

System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null

Don't forget to add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>
夜唯美灬不弃 2024-10-04 06:22:08

试试这个

这个方法的作用是,考虑单词“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();

   }

try this one

What this method does is that, Consider the word "hello world" this method turn it into "Hello World" capitalize the beginning of each word .

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();

   }
潦草背影 2024-10-04 06:22:08

这只是为了向你表明,你并没有错。

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() 来完成。 ;)

This is just to show you, that you were not that wrong.

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));

Note: This is not at all the best way to do it. This is just to show the OP that it can be done using charAt() as well. ;)

自演自醉 2024-10-04 06:22:08

这会起作用

char[] array = value.toCharArray();

array[0] = Character.toUpperCase(array[0]);

String result = new String(array);

This will work

char[] array = value.toCharArray();

array[0] = Character.toUpperCase(array[0]);

String result = new String(array);
抚笙 2024-10-04 06:22:08

您可以使用以下代码:

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);

}

You can use the following code:

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);

}
懵少女 2024-10-04 06:22:08

使用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。

Using commons.lang.StringUtils the best answer is:

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;  
}

I find it brilliant since it wraps the string with a StringBuffer. You can manipulate the StringBuffer as you wish and though using the same instance.

梦中楼上月下 2024-10-04 06:22:08

查看 ACL WordUtils。

WordUtils.capitalize("你的字符串") == "你的字符串"

如何将字符串中单词的每个第一个字母大写?

Have a look at ACL WordUtils.

WordUtils.capitalize("your string") == "Your String"

How to upper case every first letter of word in a string?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文