Posts which you will also like.

Friday, October 15, 2010

Count the no. of words in a string

This program counts the no. of words in string entered by user.This program is space resistant up to two spaces.In similar way we can make it for three or more spaces between words.

import javax.swing.JOptionPane;
class WordCount
{
private String str="";
private int wc;
private int sp;
public void wc()
{
str=JOptionPane.showInputDialog(null,"Enter a string:");
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==' ')
{
if((i<str.length()-1) && str.charAt(i+1)==' ')
{
i=i+1;
}
sp++;
}
}
JOptionPane.showMessageDialog(null,"No. of words in \""+str+"\" are:"+(sp+1));
}
public static void main(String [] args)
{
WordCount w=new WordCount();
w.wc();
}
}


OUTPUT: Enter a string:Hi how are you?
                 No. of words in "Hi how are you?" are:4
 

No comments:

Post a Comment

Your comment may wait for moderation....

DMCA.com Protected by Copyscape Online Plagiarism Tool