如何使用Java将字符串中的单词的首字母大写?


223

字符串示例

one thousand only
two hundred
twenty
seven

如何更改大写字母字符串的第一个字符,而不更改其他字母的大小写?

更改后应该是:

One thousand only
Two hundred
Twenty
Seven

注意:我不想使用apache.commons.lang.WordUtils来执行此操作。


1
@eat_a_lemon:使用Character.toUpperCase()更好,因为它可以处理az以外的其他情况(例如,数字,标点符号,带变音符号的字母,非拉丁字符)。
西蒙·尼克森

Answers:


544

如果您只想将名为的字符串的首字母大写,input而剩下的则不用管它:

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

现在output将拥有您想要的。input在使用此字符之前,请检查您的字符长度是否至少为一个字符,否则会出现异常。


37
另外,我首先将整个输入变为小写,或如下所示重新编写示例:字符串输出= input.substring(0,1).toUpperCase()+ input.substring(1).toLowerCase();
David Brossard

2
而且您想检查字符串的长度,因为它可能是1个字母字符串,甚至
Marek

1
我在这里找到它用于创建吸气和塞特名字,因此,对其余字符串使用LowerCase会破坏字段命名。给出的答案对我来说是完美的。
kaiser

85
public String capitalizeFirstLetter(String original) {
    if (original == null || original.length() == 0) {
        return original;
    }
    return original.substring(0, 1).toUpperCase() + original.substring(1);
}

只是...一个完整的解决方案,我认为这最终只是结合了其他所有人最终发布的内容= P。


12
真好 我对其进行了“单线处理”: return original.length() == 0 ? original : original.substring(0, 1).toUpperCase() + original.substring(1);
mharper

2
@mharper:,if length() == 0我们不能确定地说这是它"",而不是返回它original吗?一口气节省了我们几个字符。我问是因为我觉得Java是一种充满陷阱的语言,老实说,如果还有其他方法可以使字符串长度为零,我不会感到惊讶。
ArtOfWarfare 2015年

您说出所有真理@ArtOfWarfare。
mharper'3

注意:您可能还希望使用非英语字母。在这种情况下,您应该在toUpperCase()方法中指定语言环境。
Makalele

不能将其String.toUpperCase(Locale)用于任意字符串,因为语言环境必须匹配文本。是的,应该使用它,但是并不总是清楚该Locale使用哪个...
Christopher Schultz,

81

最简单的方法是使用org.apache.commons.lang.StringUtils

StringUtils.capitalize(Str);


8
这里有一点小注释。它仅适用于尚未大写的字符串。
乔伯特'16

5
@jobbert请澄清您的评论。如果字符串已经被大写,那么尽管它是一个名为的方法,但会否取消大写capitalize呢?
心教堂



6
String sentence = "ToDAY   WeAthEr   GREat";    
public static String upperCaseWords(String sentence) {
        String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
        String newSentence = "";
        for (String word : words) {
            for (int i = 0; i < word.length(); i++)
                newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase(): 
                    (i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
        }

        return newSentence;
    }
//Today Weather Great

这不能回答OP的问题。由于它改变了其他字母的大小写。
Lieuwe Rooijakkers,

看问题。可能您没有很好地解决这个问题。
SametÖZTOPRAK19年

3
String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
    {
        if(s.charAt(i)==' ')
        {
            c=Character.toUpperCase(s.charAt(i+1));
            s=s.substring(0, i) + c + s.substring(i+2);
        }
    }
    t.setText(s);

2
这会将每个单词的首字母大写,而不是整个字符串的首字母大写。请参阅OP提供的示例。如果字符串末尾有空格,也可能会出现问题。
tobias_k 2012年

2

在这里,您去了(希望这可以给您一个主意):

/*************************************************************************
 *  Compilation:  javac Capitalize.java
 *  Execution:    java Capitalize < input.txt
 * 
 *  Read in a sequence of words from standard input and capitalize each
 *  one (make first letter uppercase; make rest lowercase).
 *
 *  % java Capitalize
 *  now is the time for all good 
 *  Now Is The Time For All Good 
 *  to be or not to be that is the question
 *  To Be Or Not To Be That Is The Question 
 *
 *  Remark: replace sequence of whitespace with a single space.
 *
 *************************************************************************/

public class Capitalize {

    public static String capitalize(String s) {
        if (s.length() == 0) return s;
        return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    }

    public static void main(String[] args) {
        while (!StdIn.isEmpty()) {
            String line = StdIn.readLine();
            String[] words = line.split("\\s");
            for (String s : words) {
                StdOut.print(capitalize(s) + " ");
            }
            StdOut.println();
        }
    }

}

并且不更改其他字母的大小写。同时您的使用StdInStdOut是不是很Java的-Y。:-)
西蒙·尼克森,

2

它只需要一个简单的行代码即可。如果这样,String A = scanner.nextLine(); 则需要编写此代码以显示首字母大写的字符串。

System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));

现在完成了。


1

使用StringTokenizer类的示例:

String st = "  hello all students";
String st1;
char f;
String fs="";
StringTokenizer a= new StringTokenizer(st);
while(a.hasMoreTokens()){   
        st1=a.nextToken();
        f=Character.toUpperCase(st1.charAt(0));
        fs+=f+ st1.substring(1);
        System.out.println(fs);
} 

1

StringBuilder的解决方案:

value = new StringBuilder()
                .append(value.substring(0, 1).toUpperCase())
                .append(value.substring(1))
                .toString();

..根据之前的答案


1

将所有内容加在一起,在字符串开头修剪一些多余的空白是个好主意。否则,.substring(0,1).toUpperCase将尝试大写空白。

    public String capitalizeFirstLetter(String original) {
        if (original == null || original.length() == 0) {
            return original;
        }
        return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
    }

1

我的功能方法。在整个段落中,其capstil都在whitescape之后的句子中第一个字符。

要仅使单词的第一个字符具有容量,只需删除.split(“”)

           b.name.split(" ")
                 .filter { !it.isEmpty() }
                 .map { it.substring(0, 1).toUpperCase() 
                 +it.substring(1).toLowerCase() }
                  .joinToString(" ")

1

2019年7月更新

当前,用于执行此操作的最新库函数包含在 org.apache.commons.lang3.StringUtils

import org.apache.commons.lang3.StringUtils;

StringUtils.capitalize(myString);

如果您使用的是Maven,请在pom.xml中导入依赖项:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.9</version>
</dependency>

1

即使对于“简单”代码,我也会使用库。关键不是代码本身,而是涉及异常情况的已经存在的测试用例。可以是null,空字符串,其他语言的字符串。

单词操纵部分已移出Apache Commons Lang。现在将其放置在Apache Commons Text中。通过https://search.maven.org/artifact/org.apache.commons/commons-text获取。

您可以从Apache Commons Text 使用WordUtils.capitalize(String str)。它比您要求的功能强大。它也可以大写字体(例如,固定"oNe tousand only")。

由于它可以处理完整的文本,因此必须告诉它仅将第一个单词大写。

WordUtils.capitalize("one thousand only", new char[0]);

完整的JUnit类可启用以下功能:

package io.github.koppor;

import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class AppTest {

  @Test
  void test() {
    assertEquals("One thousand only", WordUtils.capitalize("one thousand only", new char[0]));
  }

}

1

如果您只想大写第一个字母,则可以使用以下代码

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

1

实际上,如果避免在这种情况下+使用操作员,则将获得最佳性能concat()。这是仅合并2个字符串的最佳选择(尽管对于许多字符串而言并不太好)。在这种情况下,代码如下所示:

String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));


0

给定input字符串:

Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase()

0

您可以尝试以下代码:

public string capitalize(str) {
    String[] array = str.split(" ");
    String newStr;
    for(int i = 0; i < array.length; i++) {
        newStr += array[i].substring(0,1).toUpperCase() + array[i].substring(1) + " ";
    }
    return newStr.trim();
}

0
public static String capitalize(String str){
        String[] inputWords = str.split(" ");
        String outputWords = "";
        for (String word : inputWords){
            if (!word.isEmpty()){
                outputWords = outputWords + " "+StringUtils.capitalize(word);
            }
        }
        return outputWords;
    }

0

我想在接受的答案上添加NULL检查和IndexOutOfBoundsException。

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

Java代码:

  class Main {
      public static void main(String[] args) {
        System.out.println("Capitalize first letter ");
        System.out.println("Normal  check #1      : ["+ captializeFirstLetter("one thousand only")+"]");
        System.out.println("Normal  check #2      : ["+ captializeFirstLetter("two hundred")+"]");
        System.out.println("Normal  check #3      : ["+ captializeFirstLetter("twenty")+"]");
        System.out.println("Normal  check #4      : ["+ captializeFirstLetter("seven")+"]");

        System.out.println("Single letter check   : ["+captializeFirstLetter("a")+"]");
        System.out.println("IndexOutOfBound check : ["+ captializeFirstLetter("")+"]");
        System.out.println("Null Check            : ["+ captializeFirstLetter(null)+"]");
      }

      static String captializeFirstLetter(String input){
             if(input!=null && input.length() >0){
                input = input.substring(0, 1).toUpperCase() + input.substring(1);
            }
            return input;
        }
    }

输出:

Normal  check #1      : [One thousand only]
Normal  check #2      : [Two hundred]
Normal  check #3      : [Twenty]
Normal  check #4      : [Seven]
Single letter check   : [A]
IndexOutOfBound check : []
Null Check            : [null]

0

以下内容将为您提供相同的一致输出,而不管您的inputString的值如何:

if(StringUtils.isNotBlank(inputString)) {
    inputString = StringUtils.capitalize(inputString.toLowerCase());
}

0

1.使用字符串substring()方法

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

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

现在,只需调用capitalize()将字符串的首字母转换为大写的方法即可:

System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null

2. Apache Commons Lang

StringUtilsCommons Lang中的类提供了capitalize()可用于此目的的方法:

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文件中(仅适用于Maven):

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

这是一篇文章,详细解释这两种方法。


-1
class Test {
     public static void main(String[] args) {
        String newString="";
        String test="Hii lets cheCk for BEING String";  
        String[] splitString = test.split(" ");
        for(int i=0; i<splitString.length; i++){
            newString= newString+ splitString[i].substring(0,1).toUpperCase() 
                    + splitString[i].substring(1,splitString[i].length()).toLowerCase()+" ";
        }
        System.out.println("the new String is "+newString);
    }
 }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.