Word counter - Java example

preview_player
Показать описание
The program counts the number of words in a string. It removes the leading and trailing spaces of the received string. Then it searches for the space-character pattern as the indicator of a word.

You'll learn most by trying my code while watching the video.

Please post your improvement on my code on the comments.

Concepts:
For loop
Scanner class
String operations

Playlist of my Java course

Playlist of my Java examples
Рекомендации по теме
Комментарии
Автор

The logic behind it is so simple yet so elegant and impressive. Thank you yet again for these great examples.

furkanveliisk
Автор

I feel like this makes more sense and is shorter:

import java.util.ArrayList;

import java.util.Scanner;
public class WordCounter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
in.close();

ArrayList<String> words = new ArrayList<>();
for(String str : input.split(" ")) {
if(str.length() > 0) words.add(str); //account for empty strings made by .split()
}
System.out.println("Word Count: " + words.size());
}
}

jacobb.
Автор

Really helps with practicing java. Thanks !

kresh
Автор

Sir what if we don't know how many lines are in a paragraph(assuming there are lines more than one), then how can we make String userInput to store all those lines??

brocklesnar
Автор

hi, you could use split and it will return an array than print the length of array ?

ayoubelgueddari
Автор

You have better approach that is engaging.

vijayvarma
join shbcf.ru