
how to count words in string using corejava

Hi Friend,
Try the following code:
import java.util.*;
class CountWords{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("Enter string: ");
String st=input.nextLine();
int count=0;
StringTokenizer stk=new StringTokenizer(st," ");
while(stk.hasMoreTokens()){
String token=stk.nextToken();
count++;
}
System.out.println("Number of words are: "+count);
}
}
Thanks

Hello,
Try this:
import java.util.*;
class CountWords{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("Enter string: ");
String st=input.nextLine();
int count=0;
String arr[]=st.split(" ");
System.out.println("Number of words are: "+arr.length);
}
}
Thanks

import java.util.*;
import java.io.*;
class Tokensex
{
public static void main(String [] args)throws Exception
{
InputStream is= System.in;
InputStreamReader ir=new InputStreamReader(is);
BufferedReader br= new BufferedReader(ir);
char [] ch= new char[600];
int i=br.read(ch,0,ch.length);
String st1= new String(ch,0,ch.length);
int count=0;
StringTokenizer st=new StringTokenizer(st1);
while(st.hasMoreTokens())
{
String token=st.nextToken(" ");
count ++;
}
System.out.println("total no of words are:" + count);
}
};
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.