Home Tutorial Java Core Find number of words begin with the specified character

 
 

Find number of words begin with the specified character
Posted on: February 13, 2010 at 12:00 AM
In this section, you will learn how to count the number of words that begin with the specified character from the string.

Count number of words begin with the specified character

In this section, you will learn how to count the number of words that begin with the specified character from the string. To do this, we have allowed the user to input a sentence or a string and a character to search. Using StringTokenizer class, we have break down the string into tokens and matches the first character of every token with the input character. If found, counter will count the words.

Here is the code:

import java.util.*;

class Words {

	public static void main(String[] args) {
		int count = 0;
		Scanner input = new Scanner(System.in);
		System.out.print("Enter string:");
		String st = input.nextLine();
		System.out.print("Enter character to count:");
		String s1 = input.next();
		StringTokenizer stk = new StringTokenizer(st);
		while (stk.hasMoreTokens()) {
			String str = stk.nextToken();
			char ch = str.charAt(0);
			String s2 = Character.toString(ch);
			if (s1.equals(s2)) {
				count++;
			}
		}
		System.out.println(s1 + "-" + count);
	}
}

Output:

Enter string: Hi How are you?
Enter character to count: H
H-2

Related Tags for Find number of words begin with the specified character:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.