settingsAccountsettings
Menusettings

Q: Count All Words - Java Task

+7 votes

Write a program to count the number of words in given sentence. Use any non-letter character as word separator.

Examples:

Count All Words - Java task

asked in Java category by user sam
edited by user golearnweb

2 Answers

+2 votes
 
Best answer

Or you can use as Regex \\W+

For generating regex, I use this site: https://regex101.com/

import java.util.ArrayList;
import java.util.Scanner;

public class CountAllWords {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String[] array = scanner.nextLine().split("\\W+");

        System.out.println(array.length);
    }
}
answered by user richard8502
edited by user golearnweb
+2 votes

Here is the solution my friend. Have a look at the 6th line to understand better how to split the data:

import java.util.Scanner;

public class Pr_05_CountAllWords {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] array = scanner.nextLine().split("( )|(')|(\\-)");

        System.out.println(array.length);
    }
}
answered by user golearnweb
edited by user golearnweb
...