CountWords.java Source code

Java tutorial

Introduction

Here is the source code for CountWords.java

Source

Regular Expression   Explanation

\\t                  A tab character

\\n                  A newline character

\\|                  A vertical bar

\\s                  Any white space character

\\s+                 One or more occurrences of any white space character

import java.util.Scanner;

public class CountWords
{
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args)
    {
        System.out.print("Enter a string: ");
        String s = sc.nextLine();
        String[] word = s.split("\\s+");
        for (String w: word)
            System.out.println(w);
    }
}