如何实现字符串每个单词首字母大写?Java代码问题排查
如何将字符串中每个单词的首字母大写?
嘿,我懂你遇到的问题了!你当前的代码只能让整个字符串的首字母大写,剩下的所有字符都转成小写,这就导致第二个单词的首字母也被改成小写了,没法实现每个单词首字母大写的效果对吧?
原代码的问题分析
你的代码逻辑是:把字符串第一个字符转大写,然后从索引1开始的所有字符统一转小写。对于输入"heLlo wOrLd",处理后第二个单词的首字母w会被强制转成小写,所以最终得到"Hello world",而不是预期的"Hello World"。
解决方案1:手动分割单词处理(无第三方依赖)
我们可以把字符串按空格分割成单个单词,逐个处理每个单词的首字母大写、其余字母小写,最后再拼接成完整字符串:
public static void main(String args[]) { String input = "heLlo wOrLd"; String[] words = input.split(" "); StringBuilder outputBuilder = new StringBuilder(); for (String word : words) { if (word.isEmpty()) { outputBuilder.append(" "); continue; } // 处理单个单词:首字母大写,其余字符小写 String processedWord = word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase(); outputBuilder.append(processedWord).append(" "); } // 移除末尾多余的空格 String output = outputBuilder.toString().trim(); System.out.println(output); // 输出:Hello World }
解决方案2:使用Apache Commons Lang工具类(更简洁)
如果你可以引入第三方库,Apache Commons Lang的WordUtils.capitalizeFully()方法正好能满足需求——它会自动将每个单词的首字母转为大写,其余字母转为小写:
import org.apache.commons.lang3.WordUtils; public static void main(String args[]) { String input = "heLlo wOrLd"; String output = WordUtils.capitalizeFully(input); System.out.println(output); // 输出:Hello World }
注意:使用这个方法需要先引入Apache Commons Lang依赖,比如Maven项目可以在pom.xml中添加:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.14.0</version> </dependency>
内容的提问来源于stack exchange,提问作者user13153470




