关于java:如何在字符串中每个单词首字母大写?

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

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Capitalize First Char of Each Word in a String Java

我有一个字符串:"Hello Good Old World",我想把每个单词的第一个字母都大写,而不是用.to upper case()括起来的整个字符串。有没有一个现有的Java助手来完成这个工作?


看看acl wordutils。

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


这是密码

1
2
3
4
5
6
7
8
9
10
11
12
13
    String source ="hello good old world";
    StringBuffer res = new StringBuffer();

    String[] strArr = source.split("");
    for (String str : strArr) {
        char[] stringArray = str.trim().toCharArray();
        stringArray[0] = Character.toUpperCase(stringArray[0]);
        str = new String(stringArray);

        res.append(str).append("");
    }

    System.out.print("Result:" + res.toString().trim());


1
2
sString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);


我不知道是否有一个功能,但如果没有现有的功能,这个功能可以完成工作:

1
2
3
4
5
6
7
8
9
10
String s ="here are a bunch of words";

final StringBuilder result = new StringBuilder(s.length());
String[] words = s.split("\\s");
for(int i=0,l=words.length;i<l;++i) {
  if(i>0) result.append("");      
  result.append(Character.toUpperCase(words[i].charAt(0)))
        .append(words[i].substring(1));

}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.apache.commons.lang.WordUtils;

public class CapitalizeFirstLetterInString {
    public static void main(String[] args) {
        // only the first letter of each word is capitalized.
        String wordStr = WordUtils.capitalize("this is first WORD capital test.");
        //Capitalize method capitalizes only first character of a String
        System.out.println("wordStr=" + wordStr);

        wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
        // This method capitalizes first character of a String and make rest of the characters lowercase
        System.out.println("wordStr =" + wordStr );
    }
}

输出:

这是第一个词的大写测试。

这是第一个词的大写测试。


这是一个非常简单、紧凑的解决方案。str包含要对其执行大写操作的变量。

1
2
3
4
5
6
7
8
StringBuilder b = new StringBuilder(str);
int i = 0;
do {
  b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
  i =  b.indexOf("", i) + 1;
} while (i > 0 && i < b.length());

System.out.println(b.toString());

最好使用StringBuilder,因为字符串是不可变的,并且为每个单词生成新字符串的效率很低。


尝试比将字符串拆分为多个字符串更有效地提高内存利用率,并使用Darshana斯里兰卡展示的策略。此外,处理单词之间的所有空白,而不仅仅是""字符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static String UppercaseFirstLetters(String str)
{
    boolean prevWasWhiteSp = true;
    char[] chars = str.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        if (Character.isLetter(chars[i])) {
            if (prevWasWhiteSp) {
                chars[i] = Character.toUpperCase(chars[i]);    
            }
            prevWasWhiteSp = false;
        } else {
            prevWasWhiteSp = Character.isWhitespace(chars[i]);
        }
    }
    return new String(chars);
}


1
2
3
4
5
6
7
8
9
10
11
12
    String s ="java is an object oriented programming language.";      
    final StringBuilder result = new StringBuilder(s.length());    
    String words[] = s.split("\"); // space found then split it  
    for (int i = 0; i < words.length; i++)
         {
    if (i > 0){
    result.append("
");
    }  
    result.append(Character.toUpperCase(words[i].charAt(0))).append(
                words[i].substring(1));  
    }  
    System.out.println(result);

输出:Java是一种面向对象的编程语言。


您还可以查看StringUtils库。它有很多很酷的东西。


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
import java.util.Scanner;
public class CapitolizeOneString {

    public static void main(String[] args)
    {
        Scanner  scan = new Scanner(System.in);
        System.out.print(" Please enter Your word      =");
        String str=scan.nextLine();

        printCapitalized( str );
    }  // end main()

    static void printCapitalized( String str ) {
        // Print a copy of str to standard output, with the
        // first letter of each word in upper case.
        char ch;       // One of the characters in str.
        char prevCh;   // The character that comes before ch in the string.
        int i;         // A position in str, from 0 to str.length()-1.
        prevCh = '.';  // Prime the loop with any non-letter character.
        for ( i = 0;  i < str.length();  i++ ) {
            ch = str.charAt(i);
            if ( Character.isLetter(ch)  &&  ! Character.isLetter(prevCh) )
                System.out.print( Character.toUpperCase(ch) );
            else
                System.out.print( ch );
            prevCh = ch;  // prevCh for next iteration is ch.
        }
        System.out.println();
    }  
}  // end class


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
package com.raj.samplestring;

/**
 * @author gnagara
 */

public class SampleString {

    /**
     * @param args
     */

    public static void main(String[] args) {
       String[] stringArray;
       String givenString ="ramu is Arr Good boy";

       stringArray = givenString.split("");


       for(int i=0; i<stringArray.length;i++){
           if(!Character.isUpperCase(stringArray[i].charAt(0))){
               Character c = stringArray[i].charAt(0);
               Character change = Character.toUpperCase(c);

               StringBuffer ss = new StringBuffer(stringArray[i]);
               ss.insert(0, change);
               ss.deleteCharAt(1);
               stringArray[i]= ss.toString();
           }
       }
       for(String e:stringArray){
           System.out.println(e);
      }
    }
}


我的代码在阅读了以上几个答案之后。

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
/**
 * Returns the given underscored_word_group as a Human Readable Word Group.
 * (Underscores are replaced by spaces and capitalized following words.)
 *
 * @param pWord
 *            String to be made more readable
 * @return Human-readable string
 */

public static String humanize2(String pWord)
{
    StringBuilder sb = new StringBuilder();
    String[] words = pWord.replaceAll("_","").split("\\s");
    for (int i = 0; i < words.length; i++)
    {
        if (i > 0)
            sb.append("");
        if (words[i].length() > 0)
        {
            sb.append(Character.toUpperCase(words[i].charAt(0)));
            if (words[i].length() > 1)
            {
                sb.append(words[i].substring(1));
            }
        }
    }
    return sb.toString();
}


下面是一个简单的解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
public class CapitalFirstLetters {

 public static void main(String[] args) {
    String word ="it's java, baby!";
    String[] wordSplit;
    String wordCapital ="";
    wordSplit = word.split("");
    for (int i = 0; i < wordSplit.length; i++) {
        wordCapital = wordSplit[i].substring(0, 1).toUpperCase() + wordSplit[i].substring(1) +"";
    }
    System.out.println(wordCapital);
 }}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class WordChangeInCapital{

   public static void main(String[]  args)
   {
      String s="this is string example";
      System.out.println(s);
      //this is input data.
      //this example for a string where each word must be started in capital letter
      StringBuffer sb=new StringBuffer(s);
      int i=0;
      do{
        b.replace(i,i+1,sb.substring(i,i+1).toUpperCase());
        i=b.indexOf("",i)+1;
      } while(i>0 && i<sb.length());
      System.out.println(sb.length());
   }

}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
public String UpperCaseWords(String line)
{
    line = line.trim().toLowerCase();
    String data[] = line.split("\\s");
    line ="";
    for(int i =0;i< data.length;i++)
    {
        if(data[i].length()>1)
            line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+"";
        else
            line = line + data[i].toUpperCase();
    }
    return line.trim();
}


使用regex简单得多:

1
2
3
4
5
6
7
8
9
10
Pattern spaces=Pattern.compile("\\s+[a-z]");      
Matcher m=spaces.matcher(word);    
StringBuilder capitalWordBuilder=new StringBuilder(word.substring(0,1).toUpperCase());
int prevStart=1;
        while(m.find()) {
                capitalWordBuilder.append(word.substring(prevStart,m.end()-1));
                capitalWordBuilder.append(word.substring(m.end()-1,m.end()).toUpperCase());
                prevStart=m.end();
        }  
        capitalWordBuilder.append(word.substring(prevStart,word.length()));

输入输出:"这个句子有奇怪的大写字母"

这个句子有奇怪的大写字母