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


421

Java中是否内置了一个函数,该函数可以大写字符串中每个单词的第一个字符,而不会影响其他单词?

例子:

  • jon skeet -> Jon Skeet
  • miles o'Brien-> Miles O'Brien(B仍然是大写字母,这排除了标题大小写)
  • old mcdonald-> Old Mcdonald*

*(Old McDonald也可以找到,但我不希望它这么聪明。)

快速浏览一下Java String Documentation仅显示toUpperCase()toLowerCase(),当然它们并不能提供所需的行为。自然,这两个函数将Google的搜索结果作为主导。似乎必须已经发明了一个轮子,所以问这个问题不会有任何伤害,因此我将来可以使用它。


18
old mcdonald呢 那应该变成Old McDonald吗?
巴特·基尔斯

2
我不希望该功能这么聪明。(尽管如果您有一个,我会很高兴看到它。)只需在空格后的第一个字母上方,但忽略其余的字母。
WillfulWizard,2009年


1
无论如何,您将无法找到一种能够在事实发生后正确处理名称大写的算法……只要有成对的名称,其中任何一个对特定的人(例如MacDonald和Macdonald)可能都是正确的,该函数就会无法知道哪个是正确的。尽管您仍然会弄错一些名称(例如冯·诺伊曼),但最好还是做一些您想做的事情。
Dave DuPlantis 2011年

试试Burger King ...
Magno C '18

Answers:


732

WordUtils.capitalize(str)(来自apache commons-text

(注意:如果您需要"fOO BAr"成为"Foo Bar",请capitalizeFully(..)改用)


5
我认为您的意思是WordUtils.capitalize(str)。有关详细信息,请参见API。
汉斯·多根

84
保持我的原则,即始终投票提及公共图书馆的答案。
拉维·瓦劳

11
要将非第一个字母更改为小写,请使用capitalizeFully(str)。
Umesh Rajbhandari'2

5
这个解决方案真的正确吗?我认为这不是!如果要大写“ LAMborghini”,则最后要“ Lamborghini”。WordUtils.capitalizeFully(str)解决方案也是如此。
basZero 2013年

3
@BasZero这是对所问问题的正确答案。我将完整版作为注释。
博佐

229

如果您只担心第一个单词的首字母大写:

private String capitalize(final String line) {
   return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}

3
这只会更改第一个单词的首字母
Chrizzz 2014年

28
确实,这是我的意图。
尼克·博尔顿

13
@nbolton-但是它显式地忽略了问题的意图,并且在该示例中给出的特殊情况下失败了,并且它对先前给出的答案几乎没有增加或没有增加!
David Manheim 2014年

17
这段代码不是崩溃安全的!想象line为空或具有<2的长度
STK

1
仍然,返回Character.toUpperCase(word.charAt(0))+ word.substring(1).toLowerCase()
Exceptyon

72

以下方法根据所有字母在空格或其他特殊字符附近的位置将其转换为大写/小写。

public static String capitalizeString(String string) {
  char[] chars = string.toLowerCase().toCharArray();
  boolean found = false;
  for (int i = 0; i < chars.length; i++) {
    if (!found && Character.isLetter(chars[i])) {
      chars[i] = Character.toUpperCase(chars[i]);
      found = true;
    } else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
      found = false;
    }
  }
  return String.valueOf(chars);
}

我会改进和简化环路条件:if(Character.isLetter(chars[i])) { if(!found) { chars[i] = Character.toUpperCase(chars[i]); } found = true; } else { found = false; }
银行家2012年

@bancer,在您的示例中,您无法控制哪些字符后不会跟大写字母。
True Soft

@TrueSoft,我不了解您。为什么需要控制大写字母后面的字符?据我了解,重要的是前面的字符不能是字母,而我的示例可以确保做到这一点。只需将您的if-else-if块替换为我的if-else块并运行测试。
银行家2012年

@TrueSoft,为清楚起见,我将重命名foundpreviousCharIsLetter
银行家2012年

9
我喜欢不使用commons库的答案,因为有时您不能使用它。
Heckman

38

试试这个非常简单的方法

示例namedString =“ ram是好孩子”

public static String toTitleCase(String givenString) {
    String[] arr = givenString.split(" ");
    StringBuffer sb = new StringBuffer();

    for (int i = 0; i < arr.length; i++) {
        sb.append(Character.toUpperCase(arr[i].charAt(0)))
            .append(arr[i].substring(1)).append(" ");
    }          
    return sb.toString().trim();
}  

输出将是:Ram Is Good Boy


1
此代码导致我们的服务器崩溃:java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0
Chrizzz 2014年

32
@Chrizzz,所以不要提交未测试的代码...如果提供空字符串,则确实会崩溃。你的错,不是尼兰的错。
2014年

1
如果末尾有空格,那么它会崩溃,然后我首先添加trim()并用空格分割字符串。它工作得非常好
Hanuman

如果有人正在寻找其Kotlin版本,则为:stackoverflow.com/a/55390188/1708390
错误发生

16

我写了一个小类,以大写String中的所有单词。

可选multiple delimiters,每个都有其行为(在处理诸如此类的案例之前,之后或两者同时进行大写O'Brian);

可选的Locale;

不要休息Surrogate Pairs

现场演示

输出:

====================================
 SIMPLE USAGE
====================================
Source: cApItAlIzE this string after WHITE SPACES
Output: Capitalize This String After White Spaces

====================================
 SINGLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string ONLY before'and''after'''APEX
Output: Capitalize this string only beforE'AnD''AfteR'''Apex

====================================
 MULTIPLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string AFTER SPACES, BEFORE'APEX, and #AFTER AND BEFORE# NUMBER SIGN (#)
Output: Capitalize This String After Spaces, BeforE'apex, And #After And BeforE# Number Sign (#)

====================================
 SIMPLE USAGE WITH CUSTOM LOCALE
====================================
Source: Uniforming the first and last vowels (different kind of 'i's) of the Turkish word D[İ]YARBAK[I]R (DİYARBAKIR) 
Output: Uniforming The First And Last Vowels (different Kind Of 'i's) Of The Turkish Word D[i]yarbak[i]r (diyarbakir) 

====================================
 SIMPLE USAGE WITH A SURROGATE PAIR 
====================================
Source: ab 𐐂c de à
Output: Ab 𐐪c De À

注意:首字母将始终大写(如果不希望,请编辑源代码)。

请分享您的评论,并帮助我发现错误或改善代码...

码:

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class WordsCapitalizer {

    public static String capitalizeEveryWord(String source) {
        return capitalizeEveryWord(source,null,null);
    }

    public static String capitalizeEveryWord(String source, Locale locale) {
        return capitalizeEveryWord(source,null,locale);
    }

    public static String capitalizeEveryWord(String source, List<Delimiter> delimiters, Locale locale) {
        char[] chars; 

        if (delimiters == null || delimiters.size() == 0)
            delimiters = getDefaultDelimiters();                

        // If Locale specified, i18n toLowerCase is executed, to handle specific behaviors (eg. Turkish dotted and dotless 'i')
        if (locale!=null)
            chars = source.toLowerCase(locale).toCharArray();
        else 
            chars = source.toLowerCase().toCharArray();

        // First charachter ALWAYS capitalized, if it is a Letter.
        if (chars.length>0 && Character.isLetter(chars[0]) && !isSurrogate(chars[0])){
            chars[0] = Character.toUpperCase(chars[0]);
        }

        for (int i = 0; i < chars.length; i++) {
            if (!isSurrogate(chars[i]) && !Character.isLetter(chars[i])) {
                // Current char is not a Letter; gonna check if it is a delimitrer.
                for (Delimiter delimiter : delimiters){
                    if (delimiter.getDelimiter()==chars[i]){
                        // Delimiter found, applying rules...                       
                        if (delimiter.capitalizeBefore() && i>0 
                            && Character.isLetter(chars[i-1]) && !isSurrogate(chars[i-1]))
                        {   // previous character is a Letter and I have to capitalize it
                            chars[i-1] = Character.toUpperCase(chars[i-1]);
                        }
                        if (delimiter.capitalizeAfter() && i<chars.length-1 
                            && Character.isLetter(chars[i+1]) && !isSurrogate(chars[i+1]))
                        {   // next character is a Letter and I have to capitalize it
                            chars[i+1] = Character.toUpperCase(chars[i+1]);
                        }
                        break;
                    }
                } 
            }
        }
        return String.valueOf(chars);
    }


    private static boolean isSurrogate(char chr){
        // Check if the current character is part of an UTF-16 Surrogate Pair.  
        // Note: not validating the pair, just used to bypass (any found part of) it.
        return (Character.isHighSurrogate(chr) || Character.isLowSurrogate(chr));
    }       

    private static List<Delimiter> getDefaultDelimiters(){
        // If no delimiter specified, "Capitalize after space" rule is set by default. 
        List<Delimiter> delimiters = new ArrayList<Delimiter>();
        delimiters.add(new Delimiter(Behavior.CAPITALIZE_AFTER_MARKER, ' '));
        return delimiters;
    } 

    public static class Delimiter {
        private Behavior behavior;
        private char delimiter;

        public Delimiter(Behavior behavior, char delimiter) {
            super();
            this.behavior = behavior;
            this.delimiter = delimiter;
        }

        public boolean capitalizeBefore(){
            return (behavior.equals(Behavior.CAPITALIZE_BEFORE_MARKER)
                    || behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
        }

        public boolean capitalizeAfter(){
            return (behavior.equals(Behavior.CAPITALIZE_AFTER_MARKER)
                    || behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
        }

        public char getDelimiter() {
            return delimiter;
        }
    }

    public static enum Behavior {
        CAPITALIZE_AFTER_MARKER(0),
        CAPITALIZE_BEFORE_MARKER(1),
        CAPITALIZE_BEFORE_AND_AFTER_MARKER(2);                      

        private int value;          

        private Behavior(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }           
    } 

15
String toBeCapped = "i want this sentence capitalized";

String[] tokens = toBeCapped.split("\\s");
toBeCapped = "";

for(int i = 0; i < tokens.length; i++){
    char capLetter = Character.toUpperCase(tokens[i].charAt(0));
    toBeCapped +=  " " + capLetter + tokens[i].substring(1);
}
toBeCapped = toBeCapped.trim();

1
嗯,我认为for循环的第二行应为:toBeCapped + =“” + capLetter + tokens [i] .substring(1,tokens [i] .length());
jengelsma 2012年

1
但是此解决方案将在开始时添加一个空格。因此,您可能需要做左修剪。
Kamalakannan J 2015年

13

我在Java 8中提出了一个易于阅读的解决方案。

public String firstLetterCapitalWithSingleSpace(final String words) {
    return Stream.of(words.trim().split("\\s"))
    .filter(word -> word.length() > 0)
    .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
    .collect(Collectors.joining(" "));
}

可以在这里找到该解决方案的要点:https : //gist.github.com/Hylke1982/166a792313c5e2df9d31


10

使用org.apache.commons.lang.StringUtils使其非常简单。

capitalizeStr = StringUtils.capitalize(str);

2
@Ash StringUtils.capitalise(str)已弃用。参见:commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/…–
Navigatron

这只会大写字符串的第一个字符,而不是字符串中每个单词的第一个字符。仅弃用WordUtils是因为它已从公共语言转换为公共文本commons.apache.org/proper/commons-text/javadocs/api-release/org/…–
opticyclic

使用外部库完成少量任务不是一个好主意。
堆栈溢出

7

用这个简单的代码

String example="hello";

example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());

System.out.println(example);

结果:您好


6
HELLO会返回HELLO,但应该是Hello,所以您应该在第二个SubString中使用toLowerCase()
Trikaldarshi 2013年

5

我正在使用以下功能。我认为它的性能更快。

public static String capitalize(String text){
    String c = (text != null)? text.trim() : "";
    String[] words = c.split(" ");
    String result = "";
    for(String w : words){
        result += (w.length() > 1? w.substring(0, 1).toUpperCase(Locale.US) + w.substring(1, w.length()).toLowerCase(Locale.US) : w) + " ";
    }
    return result.trim();
}

3
串联而不是+ =时,请始终使用StringBuilder
chitgoks

2
您为什么认为它更快?
彼得·莫滕森

5

从Java 9+

您可以这样使用String::replaceAll

public static void upperCaseAllFirstCharacter(String text) {
    String regex = "\\b(.)(.*?)\\b";
    String result = Pattern.compile(regex).matcher(text).replaceAll(
            matche -> matche.group(1).toUpperCase() + matche.group(2)
    );

    System.out.println(result);
}

范例:

upperCaseAllFirstCharacter("hello this is Just a test");

产出

Hello This Is Just A Test

4

使用Split方法将字符串拆分为单词,然后使用内置的字符串函数将每个单词大写,然后附加在一起。

伪代码(ish)

string = "the sentence you want to apply caps to";
words = string.split(" ") 
string = ""
for(String w: words)

//This line is an easy way to capitalize a word
    word = word.toUpperCase().replace(word.substring(1), word.substring(1).toLowerCase())

    string += word

最后,字符串看起来像“您要应用大写的句子”


4

如果您需要大写标题,这可能会很有用。" "除了指定的字符串(例如"a"或),它都会大写每个以分隔的子字符串"the"。我还没有运行它,因为已经晚了,但是应该没问题。一次使用Apache Commons StringUtils.join()。如果愿意,可以用一个简单的循环代替它。

private static String capitalize(String string) {
    if (string == null) return null;
    String[] wordArray = string.split(" "); // Split string to analyze word by word.
    int i = 0;
lowercase:
    for (String word : wordArray) {
        if (word != wordArray[0]) { // First word always in capital
            String [] lowercaseWords = {"a", "an", "as", "and", "although", "at", "because", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "up", "yet"};
            for (String word2 : lowercaseWords) {
                if (word.equals(word2)) {
                    wordArray[i] = word;
                    i++;
                    continue lowercase;
                }
            }
        }
        char[] characterArray = word.toCharArray();
        characterArray[0] = Character.toTitleCase(characterArray[0]);
        wordArray[i] = new String(characterArray);
        i++;
    }
    return StringUtils.join(wordArray, " "); // Re-join string
}

如果字符串中包含双倍空格(对于输入而言是愚蠢的,但仅供参考),则中断。
JustTrying

4
public static String toTitleCase(String word){
    return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}

public static void main(String[] args){
    String phrase = "this is to be title cased";
    String[] splitPhrase = phrase.split(" ");
    String result = "";

    for(String word: splitPhrase){
        result += toTitleCase(word) + " ";
    }
    System.out.println(result.trim());
}

欢迎使用Stack Overflow!通常,如果答案包括对代码意图的解释,以及为什么不引入其他代码就能解决问题的原因,则答案会更有帮助。
Neuron

迄今为止最简单的解决方案,并且避免使用外部库
Billyjoker

3
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));   

System.out.println("Enter the sentence : ");

try
{
    String str = br.readLine();
    char[] str1 = new char[str.length()];

    for(int i=0; i<str.length(); i++)
    {
        str1[i] = Character.toLowerCase(str.charAt(i));
    }

    str1[0] = Character.toUpperCase(str1[0]);
    for(int i=0;i<str.length();i++)
    {
        if(str1[i] == ' ')
        {                   
            str1[i+1] =  Character.toUpperCase(str1[i+1]);
        }
        System.out.print(str1[i]);
    }
}
catch(Exception e)
{
    System.err.println("Error: " + e.getMessage());
}

对于像我这样的新手来说,这是最简单,最基本,最好的答案!
abhishah901 2015年

3

我决定再添加一个解决方案,以大写字符串中的单词:

  • 单词在这里定义为相邻的字母或数字字符;
  • 还提供代理对;
  • 该代码已针对性能进行了优化;和
  • 它仍然很紧凑。

功能:

public static String capitalize(String string) {
  final int sl = string.length();
  final StringBuilder sb = new StringBuilder(sl);
  boolean lod = false;
  for(int s = 0; s < sl; s++) {
    final int cp = string.codePointAt(s);
    sb.appendCodePoint(lod ? Character.toLowerCase(cp) : Character.toUpperCase(cp));
    lod = Character.isLetterOrDigit(cp);
    if(!Character.isBmpCodePoint(cp)) s++;
  }
  return sb.toString();
}

示例调用:

System.out.println(capitalize("An à la carte StRiNg. Surrogate pairs: 𐐪𐐪."));

结果:

An À La Carte String. Surrogate Pairs: 𐐂𐐪.

3

采用:

    String text = "jon skeet, miles o'brien, old mcdonald";

    Pattern pattern = Pattern.compile("\\b([a-z])([\\w]*)");
    Matcher matcher = pattern.matcher(text);
    StringBuffer buffer = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(buffer, matcher.group(1).toUpperCase() + matcher.group(2));
    }
    String capitalized = matcher.appendTail(buffer).toString();
    System.out.println(capitalized);

与toLowerCase完美配合->“ Matcher matcher = pattern.matcher(text.toLowerCase());” (对于“ JOHN DOE”之类的输入文字)
smillien62 '19

3

有多种方法可以转换首字母大写的首字母。我有个主意。很简单:

public String capitalize(String str){

     /* The first thing we do is remove whitespace from string */
     String c = str.replaceAll("\\s+", " ");
     String s = c.trim();
     String l = "";

     for(int i = 0; i < s.length(); i++){
          if(i == 0){                              /* Uppercase the first letter in strings */
              l += s.toUpperCase().charAt(i);
              i++;                                 /* To i = i + 1 because we don't need to add               
                                                    value i = 0 into string l */
          }

          l += s.charAt(i);

          if(s.charAt(i) == 32){                   /* If we meet whitespace (32 in ASCII Code is whitespace) */
              l += s.toUpperCase().charAt(i+1);    /* Uppercase the letter after whitespace */
              i++;                                 /* Yo i = i + 1 because we don't need to add
                                                   value whitespace into string l */
          }        
     }
     return l;
}

感谢您尝试添加答案。这是一个合理的想法,但是请注意,已经有一些基本功能可以完成此操作,并且代码执行的功能与您提供的功能类似,并且已被接受的答案已经非常清晰地概述了所有功能。
David Manheim 2014年

2
  package com.test;

 /**
   * @author Prasanth Pillai
   * @date 01-Feb-2012
   * @description : Below is the test class details
   * 
   * inputs a String from a user. Expect the String to contain spaces and    alphanumeric     characters only.
   * capitalizes all first letters of the words in the given String.
   * preserves all other characters (including spaces) in the String.
   * displays the result to the user.
   * 
   * Approach : I have followed a simple approach. However there are many string    utilities available 
   * for the same purpose. Example : WordUtils.capitalize(str) (from apache commons-lang)
   *
   */
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;

  public class Test {

public static void main(String[] args) throws IOException{
    System.out.println("Input String :\n");
    InputStreamReader converter = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(converter);
    String inputString = in.readLine();
    int length = inputString.length();
    StringBuffer newStr = new StringBuffer(0);
    int i = 0;
    int k = 0;
    /* This is a simple approach
     * step 1: scan through the input string
     * step 2: capitalize the first letter of each word in string
     * The integer k, is used as a value to determine whether the 
     * letter is the first letter in each word in the string.
     */

    while( i < length){
        if (Character.isLetter(inputString.charAt(i))){
            if ( k == 0){
            newStr = newStr.append(Character.toUpperCase(inputString.charAt(i)));
            k = 2;
            }//this else loop is to avoid repeatation of the first letter in output string 
            else {
            newStr = newStr.append(inputString.charAt(i));
            }
        } // for the letters which are not first letter, simply append to the output string. 
        else {
            newStr = newStr.append(inputString.charAt(i));
            k=0;
        }
        i+=1;           
    }
    System.out.println("new String ->"+newStr);
    }
}

2

这是一个简单的功能

public static String capEachWord(String source){
    String result = "";
    String[] splitString = source.split(" ");
    for(String target : splitString){
        result += Character.toUpperCase(target.charAt(0))
                + target.substring(1) + " ";
    }
    return result.trim();
}

1
不要使用字符串concation用于创建长字符串,这是痛苦的缓慢:stackoverflow.com/questions/15177987/...
卢卡斯克努特

2

这只是另一种方式:

private String capitalize(String line)
{
    StringTokenizer token =new StringTokenizer(line);
    String CapLine="";
    while(token.hasMoreTokens())
    {
        String tok = token.nextToken().toString();
        CapLine += Character.toUpperCase(tok.charAt(0))+ tok.substring(1)+" ";        
    }
    return CapLine.substring(0,CapLine.length()-1);
}

2

intiCap的可重用方法:

    public class YarlagaddaSireeshTest{

    public static void main(String[] args) {
        String FinalStringIs = "";
        String testNames = "sireesh yarlagadda test";
        String[] name = testNames.split("\\s");

        for(String nameIs :name){
            FinalStringIs += getIntiCapString(nameIs) + ",";
        }
        System.out.println("Final Result "+ FinalStringIs);
    }

    public static String getIntiCapString(String param) {
        if(param != null && param.length()>0){          
            char[] charArray = param.toCharArray(); 
            charArray[0] = Character.toUpperCase(charArray[0]); 
            return new String(charArray); 
        }
        else {
            return "";
        }
    }
}

2

这是我的解决方案。

今晚我遇到了这个问题,并决定进行搜索。我发现Neelam Singh的答案几乎在那里,因此我决定解决此问题(在空字符串上中断)并导致系统崩溃。

您正在寻找的方法capString(String s)如下。它将“这里只有凌晨5点”变成“这里只有凌晨5点”。

该代码是很好的注释,请尽情享受。

package com.lincolnwdaniel.interactivestory.model;

    public class StringS {

    /**
     * @param s is a string of any length, ideally only one word
     * @return a capitalized string.
     * only the first letter of the string is made to uppercase
     */
    public static String capSingleWord(String s) {
        if(s.isEmpty() || s.length()<2) {
            return Character.toUpperCase(s.charAt(0))+"";
        } 
        else {
            return Character.toUpperCase(s.charAt(0)) + s.substring(1);
        }
    }

    /**
     *
     * @param s is a string of any length
     * @return a title cased string.
     * All first letter of each word is made to uppercase
     */
    public static String capString(String s) {
        // Check if the string is empty, if it is, return it immediately
        if(s.isEmpty()){
            return s;
        }

        // Split string on space and create array of words
        String[] arr = s.split(" ");
        // Create a string buffer to hold the new capitalized string
        StringBuffer sb = new StringBuffer();

        // Check if the array is empty (would be caused by the passage of s as an empty string [i.g "" or " "],
        // If it is, return the original string immediately
        if( arr.length < 1 ){
            return s;
        }

        for (int i = 0; i < arr.length; i++) {
            sb.append(Character.toUpperCase(arr[i].charAt(0)))
                    .append(arr[i].substring(1)).append(" ");
        }
        return sb.toString().trim();
    }
}

2

1. Java 8流

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

    return Arrays.stream(str.split("\\s+"))
            .map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
            .collect(Collectors.joining(" "));
}

例子:

System.out.println(capitalizeAll("jon skeet")); // Jon Skeet
System.out.println(capitalizeAll("miles o'Brien")); // Miles O'Brien
System.out.println(capitalizeAll("old mcdonald")); // Old Mcdonald
System.out.println(capitalizeAll(null)); // null

对于foo bARto Foo Bar,将map()方法替换为以下内容:

.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase())

2. String.replaceAll()(Java 9+)

ublic static String capitalizeAll(String str) {
    if (str == null || str.isEmpty()) {
        return str;
    }

    return Pattern.compile("\\b(.)(.*?)\\b")
            .matcher(str)
            .replaceAll(match -> match.group(1).toUpperCase() + match.group(2));
}

例子:

System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java
System.out.println(capitalizeAll("i am atta")); // I Am Atta
System.out.println(capitalizeAll(null)); // null

3. Apache Commons Text

System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere
System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky!
System.out.println(WordUtils.capitalize(null)); // null

对于标题:

System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar
System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue!

有关详细信息,请查看本教程



1
String s="hi dude i                                 want apple";
    s = s.replaceAll("\\s+"," ");
    String[] split = s.split(" ");
    s="";
    for (int i = 0; i < split.length; i++) {
        split[i]=Character.toUpperCase(split[i].charAt(0))+split[i].substring(1);
        s+=split[i]+" ";
        System.out.println(split[i]);
    }
    System.out.println(s);

1
package corejava.string.intern;

import java.io.DataInputStream;

import java.util.ArrayList;

/*
 * wap to accept only 3 sentences and convert first character of each word into upper case
 */

public class Accept3Lines_FirstCharUppercase {

    static String line;
    static String words[];
    static ArrayList<String> list=new ArrayList<String>();

    /**
     * @param args
     */
    public static void main(String[] args) throws java.lang.Exception{

        DataInputStream read=new DataInputStream(System.in);
        System.out.println("Enter only three sentences");
        int i=0;
        while((line=read.readLine())!=null){
            method(line);       //main logic of the code
            if((i++)==2){
                break;
            }
        }
        display();
        System.out.println("\n End of the program");

    }

    /*
     * this will display all the elements in an array
     */
    public static void display(){
        for(String display:list){
            System.out.println(display);
        }
    }

    /*
     * this divide the line of string into words 
     * and first char of the each word is converted to upper case
     * and to an array list
     */
    public static void method(String lineParam){
        words=line.split("\\s");
        for(String s:words){
            String result=s.substring(0,1).toUpperCase()+s.substring(1);
            list.add(result);
        }
    }

}

1

如果您喜欢番石榴...

String myString = ...;

String capWords = Joiner.on(' ').join(Iterables.transform(Splitter.on(' ').omitEmptyStrings().split(myString), new Function<String, String>() {
    public String apply(String input) {
        return Character.toUpperCase(input.charAt(0)) + input.substring(1);
    }
}));

1
String toUpperCaseFirstLetterOnly(String str) {
    String[] words = str.split(" ");
    StringBuilder ret = new StringBuilder();
    for(int i = 0; i < words.length; i++) {
        ret.append(Character.toUpperCase(words[i].charAt(0)));
        ret.append(words[i].substring(1));
        if(i < words.length - 1) {
            ret.append(' ');
        }
    }
    return ret.toString();
}

1

简短而精确的方法如下:

String name = "test";

name = (name.length() != 0) ?name.toString().toLowerCase().substring(0,1).toUpperCase().concat(name.substring(1)): name;
--------------------
Output
--------------------
Test
T 
empty
--------------------

如果您尝试将名称值更改为三个值,它将正常工作。没有错误。


如果不止一个字
怎么办
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.