English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java complete list of examples
在此示例中,我们将学习如何将Java中的字符串的第一个字母转换为大写字母。
class Main { public static void main(String[] args) { //创建一个字符串 String name = "w3codebox"; //从 name 创建两个子字符串 //第一个子字符串包含 name 的第一个字母 //第二个子字符串包含剩余字母 String firstLetter = name.substring(0, 1); String remainingLetters = name.substring(1, name.length()); //将第一个字母更改为大写 firstLetter = firstLetter.toUpperCase(); //连接两个子字符串 name = firstLetter + remainingLetters; System.out.println("Name: " + name); } }
Output result
Name: w3codebox
在示例中,我们将字符串 name 的第一个字母转换为大写。
class Main { public static void main(String[] args) { //创建一个字符串 String message = "everyone loves java"; //将每个字符存储到一个char数组 char[] charArray = message.toCharArray(); boolean foundSpace = true; for(int i = 0; i < charArray.length; i++) { //If the array element is a letter if(Character.isLetter(charArray[i])) { // Check if there is a space before the letter if(foundSpace) { //Change this letter to uppercase charArray[i] = Character.toUpperCase(charArray[i]); foundSpace = false; } } else { //If the new character is not a character foundSpace = true; } } //Convert the character array to a string message = String.valueOf(charArray); System.out.println("Message: " + message); } }
Output result
Message: Everyone Loves Java
Here,
We create a string named message
We convert the string to a char array
We access each element of the char array
If the element is a space, we will convert the next element to uppercase