In this tutorial you will learn about the Java Program to print Words in Sentence and its application with practical example.
In this tutorial, we will learn to create a Java Program to print Words in Sentence using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
- in-built functions.
Words in Sentence
with the help of string’s split() function breaks the given string around matches cases with given regular expression.
Example: we take a string as shown below and then break sentence in to word using split function
string s = “hello to Java Programming”.
Output:
hello
to
java
Programming
Java Program to print Words in Sentence
In this program, we will break sentence into word using if-else and for a loop. We would first declare and initialized the required variables. Next, we will break sentence into words. Let’s have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Java program to print words of a strings class Sentance_word { public static void Words(String s) { // break String into all possible words using split() function for (String word : s.split(" ")) if (word.length() % 2 == 0) System.out.println(word); } public static void main(String[] args) { String s = "hello to java Programming". Words(s); } } |
1 2 3 4 5 |
<strong>Approach:</strong> Take a string in variable s Now split the string into words with the help of split() function in String class. here” “(space) is delimiter to break the sentence into word. As a result, the words of the string are split and returned as a string array. for (String word : s.split(" ")) if (word.length() % 2 == 0) System.out.println(word); |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- s= it will hold string.
After declaring variables we initiate values in an array[]
After splitting the sentence into word with regular expression, this method returns a charters of arrays and finally we will print words.