Words in Sentence Program in Java

Words in Sentence Program in Java
Words in Sentence Program in Java

Enter a sentence or string and print its words of string in java.

import java.util.Scanner;
/**
 *
 * @author AFAQ
 */
public class WordsInSentence
{
    public static void main(String[] args)
    {
        String st,wd="";
        int count=0,l;
        Scanner sc=new Scanner(System.in);
        
        System.out.print("Enter String: ");
        st=sc.nextLine();
        
        st=st+" ";
        
        l=st.length();
        for (int i = 0; i < l; i++)
        {
            if(st.charAt(i)==' ')
            {
                System.out.println(wd);
                wd="";
            }
            else
            {
                char ch;
                ch=st.charAt(i);
                wd=wd+ch;
            }
        }
    }
}

Output:

Enter String: this is a boy
this
is
a
boy
java tutorials learn java study java
Recent Posts