Java 如何大写字符串中单词的每个第一个字母?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1149855/
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 upper case every first letter of word in a string?
提问by Chris
I have a string: "hello good old world" and i want to upper case every first letter of every word, not the whole string with .toUpperCase(). Is there an existing java helper which does the job?
我有一个字符串:“hello good old world”,我想将每个单词的第一个字母大写,而不是使用 .toUpperCase() 将整个字符串大写。是否有现有的 Java 助手可以完成这项工作?
采纳答案by akarnokd
回答by tommyL
i dont know if there is a function but this would do the job in case there is no exsiting one:
我不知道是否有一个功能,但如果没有现有功能,这可以完成这项工作:
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));
}
回答by amoran
Also you can take a look into StringUtilslibrary. It has a bunch of cool stuff.
您也可以查看StringUtils库。它有一堆很酷的东西。
回答by Arun
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();
}
回答by Darshana Sri Lanka
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
回答by binkdm
Here's a very simple, compact solution. str contains the variable of whatever you want to do the upper case on.
这是一个非常简单、紧凑的解决方案。str 包含您想要做大写的任何变量。
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());
It's best to work with StringBuilder because String is immutable and it's inefficient to generate new strings for each word.
最好使用 StringBuilder,因为 String 是不可变的,并且为每个单词生成新字符串的效率很低。
回答by ndomanyo
Here is the code
这是代码
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());
回答by Nitu Kumari
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());
}
}
回答by nagaraju
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);
}
}
}
回答by user877139
Trying to be more memory efficient than splitting the string into multiple strings, and using the strategy shown by Darshana Sri Lanka. Also, handles all white space between words, not just the " " character.
尝试比将字符串拆分为多个字符串更有效地节省内存,并使用 Darshana Sri Lanka 展示的策略。此外,处理单词之间的所有空白,而不仅仅是 " " 字符。
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);
}