Java Programing laungage

java.util Projects

java.util Project 1

Break the String into Words

In this program, we will be learn that how we can break string into the words. The java.util.*;package is provide a method to breaking the string into words.

Previous Home Next

This program takes a string from user and breaks it into words. The given string has been broken into words based on the blank spaces between the words. This program also counts the number of words present in the string. Following are some

Methods and APIs Description

StringTokenizer(String str)

This constructor is used to creates token of the given string. It is takeing a string type value as a parameter and tokenized it. The passed string is the collection of multiple sets like: Tab character ("\t"), blank space (" "), new line character ("\n") etc.

hasMoreTokens()

This method is used to check the token created by the StringTokenizer() methods. It returns Boolean type value either true or false. If the above method returns true then the nextToken() method is called.

nextToken()

This method returns the tokenized string which is the separate word of the given string. Through the help of the available spaces this method distinguish between words.

Example


package r4r;
import java.util.*;
import java.io.*;
public class breakstringtest {
	String str;
	  int count = 0;
public static void main(String[] args)
{
	



	breakstringtest c = new breakstringtest();
}
public breakstringtest(){
try{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print("Enter the String: ");
str = br.readLine();
System.out.println("Enter String is : "+ str);
System.out.println("Break this string : ");
StringTokenizer tok = new StringTokenizer(str);
while (tok.hasMoreTokens()){
count++;
str = tok.nextToken();
System.out.println(str);
}
System.out.println("Number of Words is : "+ count);
}
catch(IOException e){}
}
}

Output


Enter the String: Ram is a god
Enter String is : Ram is a god
Break this string :
Ram
is
a
god
Number of Words is : 4

Previous Home Next