stringcharacters.java

来自「Java2入门经典第四章源码」· Java 代码 · 共 39 行

JAVA
39
字号
public class StringCharacters
{
  public static void main(String[] args)
  {
    // Text string to be analyzed
    String text = "To be or not to be, that is the question;"
                 +"Whether 'tis nobler in the mind to suffer"
                 +" the slings and arrows of outrageous fortune,"
                 +" or to take arms against a sea of troubles,"
                 +" and by opposing end them?";

    int spaces  = 0,                                 // Count of spaces
        vowels  = 0,                                 // Count of vowels
        letters = 0;                                 // Count of letters

    // Analyze all the characters in the string
    for(int i = 0; i < text.length(); i++)
    {
      // Check for vowels
      char ch = Character.toLowerCase(text.charAt(i));
      if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
        ++vowels;

      //Check for letters
      if(Character.isLetter(ch))
        ++letters;

      // Check for spaces
      if(Character.isWhitespace(ch))
        ++spaces;
    }

    System.out.println
             ("The text contained vowels:     " + vowels + "\n" + 
              "                   consonants: " + (letters-vowels) + "\n"+
              "                   spaces:     " + spaces);
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?