我有一个字符串:"hello good old world",我想将每个单词的第一个字母改为大写,而不是使用 .toUpperCase() 将整个字符串转换为大写。是否存在一个现成的 Java 工具可以完成这个任务?
可以看一下 ACL 的 WordUtils。
WordUtils.capitalize("your string") == "Your String"
以下是代码
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());
StringBuilder
的长度。既然您将调用StringBuilder.append
,则不必在每次循环迭代中创建新的char[]
和String
:只需附加大写字母,然后使用String.charAt
和String.substring
添加单词的其余部分。最后,您可能应该允许传入一个Locale
,以便使用区域设置敏感的String.toUpperCase(Locale)
。 - Christopher SchultzsString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);
我不知道是否有一个函数可以完成此任务,但如果没有现成的函数,这段代码可以实现:
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));
}
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 包含你想要大写的变量。
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,因为String是不可变的,对于每个单词生成新的字符串效率低下。
尝试比将字符串拆分为多个字符串更加节省内存,并使用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);
}
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库。它有很多很酷的东西。
在阅读几篇以上的答案后,我的代码如下。
/**
* 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();
}