1. ใช้substring()วิธีการของสตริง
public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
ตอนนี้เรียกcapitalize()เมธอดเพื่อแปลงอักษรตัวแรกของสตริงให้เป็นตัวพิมพ์ใหญ่:
System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null
2. Apache Commons Lang
StringUtilsระดับจากคอมมอนส์แลงมีcapitalize()วิธีการที่ยังสามารถนำมาใช้เพื่อวัตถุประสงค์นี้:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
เพิ่มการพึ่งพาต่อไปนี้ในpom.xmlไฟล์ของคุณ(สำหรับ Maven เท่านั้น):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
นี่คือบทความที่อธิบายรายละเอียดสองแนวทางนี้