关于Java:如何将字符串中每个单词的首字母大写

How to capitalize the first character of each word in a string

在Java中是否内置了一个函数,将字符串中每个单词的第一个字符大写,不影响其他字符吗?

实例:

  • jon skeet->jon skeet
  • miles o'Brien->miles o'Brien(b仍为资本,不包括产权案件)
  • old mcdonald->old mcdonald。*

*(old mcdonald也会被找到,但我不希望它那么聪明。)

快速查看Java字符串文档只会显示EDCOX1 7和EDCOX1 8,当然不提供所需的行为。当然,谷歌的搜索结果由这两个功能主导。它看起来像是一个已经被发明出来的轮子,所以问起来不会有什么问题,这样我将来就可以使用它了。


WordUtils.capitalize(str)(来自apache commons文本)

(注:如果你需要"fOO BAr"成为"fOO BAr"的话,用capitalizeFully(..)代替)


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

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


以下方法将所有字母转换为大写/小写,具体取决于它们在空格或其他特殊字符附近的位置。

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
}


试试这个很简单的方法

示例givenstring="ram is good boy"

1
2
3
4
5
6
7
8
9
10
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是好孩子


我已经编写了一个小类来将字符串中的所有单词大写。

可选的multiple delimiters,每个都有自己的行为(在处理O'Brian这样的案件之前、之后或两者都大写);

可选Locale

不要与Surrogate Pairs断开。

现场演示

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
====================================
 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 à

注意:第一个字母将始终大写(如果不需要,请编辑源代码)。

请分享您的意见,并帮助我发现错误或改进代码…

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
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;
        }          
    }

1
2
3
4
5
6
7
8
9
10
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();


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

1
capitalizeStr = StringUtils.capitalize(str);


我在Java 8中做了一个解决方案,它的可读性更强。

1
2
3
4
5
6
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


使用此简单代码:

1
2
3
4
5
String example="hello";

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

System.out.println(example);

结果:你好


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

1
2
3
4
5
6
7
8
9
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();
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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());
}


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

伪码

1
2
3
4
5
6
7
8
9
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

在末尾字符串看起来像"要应用大写字母的句子"


如果需要大写标题,这可能很有用。它将由""分隔的每个子字符串大写,但指定的字符串除外,如"a""the"。我还没有运行它,因为它已经晚了,不过应该很好。在某一点上使用ApacheCommons StringUtils.join()。如果您愿意,可以用一个简单的循环来代替它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
}


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

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

功能:

1
2
3
4
5
6
7
8
9
10
11
12
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();
}

示例调用:

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

结果:

1
An à La Carte String. Surrogate Pairs: ????.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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());
}


从Java 9 +

您可以这样使用String::replceAll

1
2
3
4
5
6
7
8
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);
}

例子:

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

输出

1
Hello This Is Just A Test


有很多方法可以将第一个单词的第一个字母转换为大写。我有个主意。很简单:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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;
}


这是一个简单的函数

1
2
3
4
5
6
7
8
9
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
2
3
4
5
6
7
8
9
10
    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);

这只是另一种方式:

1
2
3
4
5
6
7
8
9
10
11
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);
}

可重复使用的inticap方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    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"";
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  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 :
"
);
    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);
    }
}

这是我的解决方案。

我今晚偶然遇到这个问题,决定去调查一下。我找到了几乎就在那里的NeelamSingh的答案,所以我决定解决这个问题(用空字符串中断),并导致了系统崩溃。

您要查找的方法名为capString(String s)。它把"这里只有早上5点"变成"这里只有早上5点"。

代码的注释非常好,请尽情享受。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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();
    }
}

1
2
3
4
5
6
7
8
9
10
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);


对于在MVC中使用Velocity的用户,可以使用StringUtils类中的capitalizeFirstLetter()方法。


如果你喜欢番石榴…

1
2
3
4
5
6
7
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
2
3
4
5
6
7
8
9
10
11
12
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
2
3
4
5
6
7
8
9
10
11
12
13
 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();
    }

这一个适用于姓的案件…

使用不同类型的分隔符,并保持相同的分隔符:

  • Jean Frederic——>Jean Frederic

  • Jean Frederic——>Jean Frederic

该代码与GWT客户端协同工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static String capitalize (String givenString) {
    String Separateur =" ,.-;";
    StringBuffer sb = new StringBuffer();
    boolean ToCap = true;
    for (int i = 0; i < givenString.length(); i++) {
        if (ToCap)              
            sb.append(Character.toUpperCase(givenString.charAt(i)));
        else
            sb.append(Character.toLowerCase(givenString.charAt(i)));

        if (Separateur.indexOf(givenString.charAt(i)) >=0)
            ToCap = true;
        else
            ToCap = false;
    }          
    return sb.toString().trim();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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("
 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
2
3
String name ="test";

name = (name.length() != 0) ?name.toString().toLowerCase().substring(0,1).toUpperCase().concat(name.substring(1)): name;
1
2
3
4
5
6
7
--------------------
Output
--------------------
Test
T
empty
--------------------

如果您尝试将名称值更改为三个值中的三个,它将毫无错误地工作。无错误。


我使用雨滴图书馆的wordUppercase(String s)。因为这是我的库,这里有一个方法:

1
2
3
4
5
6
7
8
9
10
11
 /**
  * Set set first letter from every word uppercase.
  *
  * @param s - The String wich you want to convert.
  * @return The string where is the first letter of every word uppercase.
  */

 public static String wordUppercase(String s){
   String[] words = s.split("");
   for (int i = 0; i < words.length; i++) words[i] = words[i].substring(0, 1).toUpperCase() + words[i].substring(1).toLowerCase();
   return String.join("", words);
 }

希望有帮助:)


我做了一个小班级,可以用来在一个句子中通读每个单词。如果不是空格,可以更改字符串中的单词分隔符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.ecnews.ecnews_v01.Helpers;

  public class Capitalize {

  String sentence;
  String separator ="";

  public Capitalize(String sentence) {
    this.sentence = sentence;
  }

  public void setSeparator(String separator) {
    this.separator = separator;
  }

  public String getCapitalized() {
    StringBuilder capitalized = new StringBuilder("");
    for (String word : sentence.split(separator)) {
        capitalized.append(separator+Character.toUpperCase(word.charAt(0)) + word.substring(1));
    }
    return capitalized.toString().trim();
  }

}

例子:

String sourceName = new Capitalize("this is a test").getCapitalized();

sourcename将为"这是一个测试"


这是我的另一种方式

1
2
3
4
5
6
7
8
9
10
11
    StringBuilder str=new StringBuilder("pirai sudie test test");

    str.setCharAt(0,Character.toUpperCase(str.charAt(0)));

    for(int i=str.length()-1;i>=0;i--)
    {
        if(Character.isSpaceChar(str.charAt(i)))
            str.setCharAt(i+1,Character.toUpperCase(str.charAt(i+1)));
    }

    System.out.println(str);


这是解决这个问题的方法。

1
2
3
4
5
6
7
8
9
10
11
12
    String title ="this is a title";
    StringBuilder stringBuilder = new StringBuilder();
    Observable.fromArray(title.trim().split("\\s"))
        .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase())
        .toList()
        .map(wordList -> {
            for (String word : wordList) {
                stringBuilder.append(word).append("");
            }
            return stringBuilder.toString();
        })
        .subscribe(result -> System.out.println(result));

不过,我还不喜欢地图中的for循环。


以下是同一问题的Kotlin版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
fun capitalizeFirstLetterOfEveryWord(text: String): String
{
    if (text.isEmpty() || text.isBlank())
    {
        return""
    }

    if (text.length == 1)
    {
        return Character.toUpperCase(text[0]).toString()
    }

    val textArray = text.split("")
    val stringBuilder = StringBuilder()

    for ((index, item) in textArray.withIndex())
    {
        // If item is empty string, continue to next item
        if (item.isEmpty())
        {
            continue
        }

        stringBuilder
            .append(Character.toUpperCase(item[0]))

        // If the item has only one character then continue to next item because we have already capitalized it.
        if (item.length == 1)
        {
            continue
        }

        for (i in 1 until item.length)
        {
            stringBuilder
                .append(Character.toLowerCase(item[i]))
        }

        if (index < textArray.lastIndex)
        {
            stringBuilder
                .append("")
        }
    }

    return stringBuilder.toString()
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
String text="hello";
StringBuffer sb=new StringBuffer();
char[] ch=text.toCharArray();
for(int i=0;i<ch.length;i++){
    if(i==0){
        sb.append(Character.toUpperCase(ch[i]));
    }
    else{
    sb.append(ch[i]);
    }
}


text=sb.toString();
System.out.println(text);
}

既然没人用过regexp,那我们就用regexp吧。这个解决方案很有趣。:)(更新:事实上,我刚刚发现有一个regexps的答案,无论如何,我希望保留这个答案,因为它看起来更好:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Capitol
{
    public static String now(String str)
    {
        StringBuffer b = new StringBuffer();
        Pattern p = Pattern.compile("\\b(\\w){1}");
        Matcher m = p.matcher(str);
        while (m.find())
        {
            String s = m.group(1);
            m.appendReplacement(b, s.toUpperCase());
        }
        m.appendTail(b);
        return b.toString();
    }
}

用法

1
2
3
4
Capitol.now("ab cd"));
Capitol.now("winnie the Pooh"));
Capitol.now("please talk loudly!"));
Capitol.now("miles o'Brien"));


1
2
3
4
5
6
7
8
9
10
11
12
13
public void capitaliseFirstLetterOfEachWord()
{
    String value="this will capitalise first character of each word of this string";
    String[] wordSplit=value.split("");
    StringBuilder sb=new StringBuilder();

    for (int i=0;i<wordSplit.length;i++){

        sb.append(wordSplit[i].substring(0,1).toUpperCase().
                concat(wordSplit[i].substring(1)).concat(""));
    }
    System.out.println(sb);
}

我需要创建一个通用的toString(object obj)助手类函数,在这里我必须将字段名转换为所传递对象的方法名-getxxx()。

这是密码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * @author DPARASOU
 * Utility method to replace the first char of a string with uppercase but leave other chars as it is.
 * ToString()
 * @param inStr - String
 * @return String
 */

public static String firstCaps(String inStr)
{
    if (inStr != null && inStr.length() > 0)
    {
        char[] outStr = inStr.toCharArray();
        outStr[0] = Character.toUpperCase(outStr[0]);
        return String.valueOf(outStr);
    }
    else
        return inStr;
}

我的toString()实用程序是这样的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static String getToString(Object obj)
{
    StringBuilder toString = new StringBuilder();
    toString.append(obj.getClass().getSimpleName());
    toString.append("[");
    for(Field f : obj.getClass().getDeclaredFields())
    {
        toString.append(f.getName());
        toString.append("=");
        try{
            //toString.append(f.get(obj)); //access privilege issue
            toString.append(invokeGetter(obj, firstCaps(f.getName()),"get"));
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        toString.append(",");        
    }
    toString.setCharAt(toString.length()-2, ']');
    return toString.toString();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Simple answer by program:


public class StringCamelCase {
    public static void main(String[] args) {
        String[] articles = {"the","a","one","some","any"};
        String[] result = new String[articles.length];
        int i = 0;
        for (String string : articles) {
            result[i++] = toUpercaseForstChar(string);
        }

        for (String string : result) {
            System.out.println(string);
        }
    }
    public static String toUpercaseForstChar(String string){
        return new String(new char[]{string.charAt(0)}).toUpperCase() + string.substring(1,string.length());
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    s.toLowerCase().trim();
    result += Character.toUpperCase(s.charAt(0));
    result += s.substring(1, s.indexOf("") + 1);
    s = s.substring(s.indexOf("") + 1);

    do {
        if (s.contains("")) {
            result +="";
            result += Character.toUpperCase(s.charAt(0));
            result += s.substring(1, s.indexOf(""));
            s = s.substring(s.indexOf("") + 1);
        } else {
            result +="";
            result += Character.toUpperCase(s.charAt(0));
            result += s.substring(1);
            break;
        }
    } while (true);
    System.out.println(result);

最基本和最简单的理解方法(我认为):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.Scanner;

public class ToUpperCase {
    static Scanner kb = new Scanner(System.in);

    public static String capitalize(String str){
        /* Changes 1st letter of every word
           in a string to upper case
         */

        String[] ss = str.split("");
        StringBuilder[] sb = new StringBuilder[ss.length];
        StringBuilder capped = new StringBuilder("");
        str ="";

        // Capitalise letters
        for (int i = 0; i < ss.length; i++){
            sb[i] = new StringBuilder(ss[i]); // Construct and assign
            str += Character.toUpperCase(ss[i].charAt(0)); // Only caps
            //======================================================//

            // Replace 1st letters with cap letters
            sb[i].setCharAt(0, str.charAt(i));
            capped.append(sb[i].toString() +"");  // Formatting
        }
        return capped.toString();
    }

    public static void main(String[] args){
        System.out.println(capitalize(kb.nextLine()));
    }
}

//如此简单和基本

1
2
3
4
5
6
7
8
9
10
11
12
public void capalizedFirstCharOne(String str){
    char[] charArray=str.toCharArray();
    charArray[0]=Character.toUpperCase(charArray[0]);
    for(int i=1;i<charArray.length;i++){
        if(charArray[i]==' ' ){
            charArray[i+1]=Character.toUpperCase(charArray[i+1]);
        }
    }

    String result=new String(charArray);
    System.out.println(result);
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.io.*;
public class Upch2
{
   BufferedReader br= new BufferedReader( new InputStreamReader(System.in));
   public void main()throws IOException
    {
        System.out.println("Pl. Enter A Line");
        String s=br.readLine();
        String s1="";
        s=""+s;
        int len=s.length();
        s= s.toLowerCase();
        for(int j=1;j<len;j++)
         {
           char  ch=s.charAt(j);

           if(s.charAt(j-1)!=' ')
           {
             ch=Character.toLowerCase((s.charAt(j)));
           }
           else
           {
             ch=Character.toUpperCase((s.charAt(j)));
            }
            s1=s1+ch;
          }
     System.out.println(""+s1);
  }
}