Java 如何将字符串中每个单词的第一个字符大写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1892765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to capitalize the first character of each word in a string
提问by WillfulWizard
Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?
Java 中是否有一个函数可以将字符串中每个单词的第一个字符大写,并且不影响其他字符?
Examples:
例子:
jon skeet
->Jon Skeet
miles o'Brien
->Miles O'Brien
(B remains capital, this rules out Title Case)old mcdonald
->Old Mcdonald
*
jon skeet
->Jon Skeet
miles o'Brien
->Miles O'Brien
(B 仍然是大写,这排除了 Title Case)old mcdonald
->Old Mcdonald
*
*(Old McDonald
would be find too, but I don't expect it to be THAT smart.)
*(Old McDonald
也会被发现,但我不希望它那么聪明。)
A quick look at the Java String Documentationreveals only toUpperCase()
and toLowerCase()
, which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.
快速浏览一下Java 字符串文档只会发现toUpperCase()
and toLowerCase()
,这当然不会提供所需的行为。自然,谷歌搜索结果由这两个功能主导。这似乎是一个必须已经发明的轮子,所以我可以问一下,以便我将来可以使用它。
采纳答案by Bozho
WordUtils.capitalize(str)
(from apache commons-text)
WordUtils.capitalize(str)
(来自apache commons-text)
(Note: if you need "fOO BAr"
to become "Foo Bar"
, then use capitalizeFully(..)
instead)
(注意:如果您需要"fOO BAr"
成为"Foo Bar"
,请capitalizeFully(..)
改用)
回答by True Soft
The following method converts all the letters into upper/lower case, depending on their position near a space or other special chars.
以下方法将所有字母转换为大写/小写,具体取决于它们在空格或其他特殊字符附近的位置。
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);
}
回答by Suganya
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());
}
回答by Reid Mac
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();
回答by Shogo Yahagi
For those of you using Velocity in your MVC, you can use the capitalizeFirstLetter()
method from the StringUtils class.
对于在 MVC 中使用 Velocity 的人,可以使用StringUtils 类中的capitalizeFirstLetter()
方法。
回答by shraddha
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);
}
}
回答by Prasanth
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);
}
}
回答by Nick Bolton
If you're only worried about the first letter of the first word being capitalized:
如果您只担心第一个单词的首字母大写:
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
回答by Paul
Use the Split method to split your string into words, then use the built in string functions to capitalize each word, then append together.
使用 Split 方法将字符串拆分为单词,然后使用内置的字符串函数将每个单词大写,然后附加在一起。
Pseudo-code (ish)
伪代码(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
In the end string looks something like "The Sentence You Want To Apply Caps To"
最后的字符串看起来像“你想要应用大写的句子”
回答by Dominykas Mostauskis
This might be useful if you need to capitalize titles. It capitalizes each substring delimited by " "
, except for specified strings such as "a"
or "the"
. I haven't ran it yet because it's late, should be fine though. Uses Apache Commons StringUtils.join()
at one point. You can substitute it with a simple loop if you wish.
如果您需要大写标题,这可能很有用。它将每个由 分隔的子字符串大写" "
,但指定的字符串除外,例如"a"
或"the"
。我还没有运行它,因为已经晚了,不过应该没问题。StringUtils.join()
一度使用 Apache Commons 。如果你愿意,你可以用一个简单的循环代替它。
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
}