w3resource

Java: Cut out words of 3 to 6 characters length from a given sentence not more than 1024 characters

Java Basic: Exercise-239 with Solution

A search engine giant such as Google accepts thousands of web pages from around the world and categorizes them, creating a huge database of information. Search engines also analyze search keywords entered by the user and create database queries based on those keywords. In both cases, complicated processing is carried out to realize efficient retrieval, but the basics are all about cutting out words from sentences.
Write a Java program to cut out words of 3 to 6 characters length from a given sentence not more than 1024 characters.

Input:
English sentences consisting of delimiters and alphanumeric characters are given on one line.
Output: Output a word delimited by one space character on one line.

Sample Solution:

Java Code:

 import java.util.Scanner;

public class Main{
	  public static void main(String[] args) 
       {	
		Scanner sc = new Scanner(System.in);
		System.out.println("Input a sentence (1024 characters. max.)");
		String[] str = ((sc.nextLine()).replace(",", "").replace(".", "")).split(" ");
		int flag = 0;
		System.out.println("\n3 to 6 characters length of words:");
		for(String s: str){
			int l = s.length();
			if(l >= 3 && l <= 6){
				if(flag == 1){
					System.out.print(" ");
				}
					System.out.print(s);
				flag = 1;
			}
		}	
	} 
}

Sample Output:

Input a sentence (1024 characters. max.)
The quick brown fox

3 to 6 characters length of words:
The quick brown fox

Flowchart:

Flowchart: Restore the original string by entering the compressed string with this rule.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to restore the original string by entering the compressed string with this rule.
Next: Write a Java program that compute the maximum value of the sum of the passing integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.