Advertisements
Advertisements
Question
Write a program to input a sentence. Find and display the following:
- Number of words present in the sentence
- Number of letters present in the sentence
Assume that the sentence neither includes any digit nor any special character.
Code Writing
Solution
import java.util.*;
public class SQ1
{public static void main(String args[])
{Scanner in = new Scanner(System.in);
String str;
int word = (), letter = ();
char ch;
System.out.println("Enter the string");
str = in.nextLine();
str = str.trim(); // to remove any leading or trailing space
str = " " + str;
for (int i = 0; i < str.length(); i++)
{ ch = str.charAt(i);
if (ch == ' ')
{if (Character.isLetter(str.char At(i + 1)) == true)
// to prevent the counting of extra spaces in between words
word++; // number of spaces = number of words
}
else if (ch! = ' ')
letter++;
}
System.out.println("Number of words = " + word);
System.out.println("Number of letters = " + letter);
}}
shaalaa.com
Is there an error in this question or solution?
Chapter 4: String Handling - EXERCISES [Page 289]