Page 295 - ComputerScience_Class_11
P. 295

6              Scanner sc= new Scanner(System.in);
                   7              String str;

                   8              int i, l, cw=0, ca=0, cd=0;
                   9              System.out.print("Enter a sentence: ");
                  10              str=sc.nextLine();

                  11              l=str.length();

                  12              for(i=0; i<l; i++)
                  13              {
                  14                  char ch=str.charAt(i);

                  15                  if(Character.isWhitespace(ch))
                  16                  {

                  17                      cw++;
                  18                  }

                  19                  if(Character.isLetter(ch))
                  20                  {

                  21                      ca++;
                  22                  }

                  23                  if(Character.isDigit(ch))
                  24                  {

                  25                      cd++;
                  26                  }

                  27              }
                  28              System.out.println("Number of words: "+(cw+1));

                  29              System.out.println("Number of alphabets: " + ca);
                  30              System.out.println("Number of digits: "+cd);

                  31          }
                  32      }

                 The output of the preceding program is as follows:

                       BlueJ: Terminal Window - Java

                   Options

                  Enter a sentence: hello world i am back
                  Number of words: 5
                  Number of alphabets: 17
                  Number of digits: 0






                                                                                                           Strings  293
   290   291   292   293   294   295   296   297   298   299   300