Write Java program to Extract words from a given sentence


This Java program extracts the first four words from a given string and prints them to the console. The program uses the split() method to split the string into an array of words, based on the delimiter " " (a space character). The second argument to split() specifies the maximum number of words to extract, which is set to 4 in this case.

The program starts by declaring a string variable str and initializing it with the value "Tutor Joes Computer Education ". The trailing space in the string is not necessary for the program to work, but it is included for clarity.

The program then uses the split() method to split the string into an array of words, and stores the result in the string array words. The second argument to split() is set to 4, so the array will contain at most 4 words.

The program then uses a for-each loop to iterate over the elements of the words array. For each word in the array, the program prints the word to the console using System.out.println().

Overall, this program is a simple way to extract the first four words from a string in Java using the split() method. However, if the string contains less than four words, the program will simply print all of the words in the string. Additionally, if the string contains more than four words, the program will only print the first four words, which may not be desirable in all cases.

Source Code

class Extract_Word
{
	public static void main(String args[])
	{
		String str = "Tutor Joes Computer Education ";
		String [] words = str.split(" ", 4);
 
		for (String w : words)
		{
			System.out.println(w);
		}
	}
}

Output

Tutor
Joes
Computer
Education

Example Programs