将字符串中每个单词的第一个字符大写的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:Java 程序使 String 的第一个字母大写

public class Main {
  public static void main(String[] args) {

    // create a string
    String name = "tom";

    // create two substrings from name
    // first substring contains first letter of name
    // second substring contains remaining letters
    String firstLetter = name.substring(0, 1);
    String remainingLetters = name.substring(1, name.length());

    // change the first letter to uppercase
    firstLetter = firstLetter.toUpperCase();

    // join the two substrings
    name = firstLetter + remainingLetters;
    System.out.println("Name: " + name);

  }
}

输出

Name: Tom

在示例中,我们将字符串 name 的第一个字母转换为大写。

示例 2:将字符串的每个单词转换为大写

public class Main {
  public static void main(String[] args) {

    // create a string
    String message = "everyone loves java";

    // stores each characters to a char array
    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 space is present before the letter
        if(foundSpace) {

          // change the letter into uppercase
          charArray[i] = Character.toUpperCase(charArray[i]);
          foundSpace = false;
        }
      }

      else {
        // if the new character is not character
        foundSpace = true;
      }
    }

    // convert the char array to the string
    message = String.valueOf(charArray);
    System.out.println("Message: " + message);
  }
}

输出

Message: Everyone Loves Java

这里,

  • 我们创建了一个名为 message 的字符串
  • 我们将字符串转换为 char 数组
  • 我们访问 char 数组的每个元素
  • 如果元素是空格,我们将下一个元素转换为大写