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

 
 

Share on Google+Share on Google+
Find number of words begin with the specified character
Posted on: February 13, 2010 at 12:00 AM
Advertisement
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
Advertisement

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


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 13, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com