settingsAccountsettings
Menusettings

Q: Count Specified Word - Java Task

+7 votes

Write a program to find how many times a word appears in given text. The text is given at the first input line. The target word is given at the second input line. The output is an integer number. Please ignore the character casing. Consider that any non-letter character is a word separator.

Examples:

count words in java

asked in Java category by user eiorgert
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

Here'e my solution mate:

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

public class Pr_06_CountSpecifiedWord {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String[] firstIn = scanner.nextLine().toLowerCase().split("((\\s+)|('))");//EMPTY SPACES + APOSTROPHE
        String secondIn = scanner.nextLine().toLowerCase();//THE SECOND INPUT IS LOWER CASE AS WELL - SO BOTH CAN MATCH

        int counter = 0;
        for (int i = 0; i < firstIn.length; i++) {
            if (firstIn[i].equals(secondIn)) {//IT IS BETTER TO USE .equals then == !!! WHEN COMPARING STRINGS
                counter++;
            }
        }
        System.out.println(counter);
    }
}

Here's how you should compare strings in Java: https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

answered by user hues
edited by user golearnweb
...