📜  Java程序将字符中每个单词的首字符大写

📅  最后修改于: 2020-09-26 17:53:59             🧑  作者: Mango

在此示例中,我们将学习如何将字符串的第一个字母转换为Java中的大写字母。

示例1:Java程序将String首字母大写
class Main {
  public static void main(String[] args) {

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

    // 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: Programiz 

在示例中,我们将字符串 名称的首字母转换为大写。


示例2:将字符串的每个单词都转换为大写
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数组的每个元素
  • 如果元素是空格,我们将下一个元素转换为大写