Word & Character Counter — Java source
Live word, character, sentence, and paragraph counts plus reading-time estimate as you type.
This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// word-counter — Java port: word / character / sentence / paragraph counts + 200-wpm reading-time estimate.
//
// Display snippet: ports the counters from the TypeScript lib (src/lib/wordCount.ts). Java strings
// are UTF-16, so String.length() is the same unit the TS reference counts. Requires Java 11+
// (strip / isBlank mirror the JS Unicode-aware trim and blank checks).
import java.util.Arrays;
import java.util.regex.Pattern;
public final class WordCounter {
private static final Pattern SENTENCE = Pattern.compile("[^.!?]+[.!?]+");
// Words: split on whitespace runs after stripping — blank input -> 0.
public static long countWords(String t) {
String s = t.strip();
return s.isEmpty() ? 0 : s.split("\\s+").length;
}
// Total character count, whitespace included.
public static int countChars(String t) {
return t.length();
}
// Character count with all whitespace removed.
public static long countCharsNoSpaces(String t) {
return t.chars().filter(c -> !Character.isWhitespace(c)).count();
}
// Sentences: maximal runs of non-terminators each closed by one or more
// of . ! ? — the TS regex /[^.!?]+[.!?]+/g.
public static int countSentences(String t) {
return SENTENCE.matcher(t).results().mapToInt(m -> 1).sum();
}
// Paragraphs separated by one or more blank lines; blank segments don't count.
public static long countParagraphs(String t) {
return Arrays.stream(t.split("\\n{2,}")).filter(s -> !s.isBlank()).count();
}
// Reading time at 200 wpm: 0 for empty input, otherwise >= 1 minute.
// (words + 100) / 200 reproduces Math.round(words / 200.0).
public static long readingTimeMin(long words) {
if (words <= 0) return 0;
return Math.max(1, (words + 100) / 200);
}
public static void main(String[] args) {
String text = "CosmoDev counts words. Live totals update as you type!\n\n"
+ "Second paragraph? Two sentences - each with words. Zero logins needed.";
System.out.println("words: " + countWords(text)); // 20
System.out.println("chars: " + countChars(text)); // 126
System.out.println("no spaces: " + countCharsNoSpaces(text)); // 106
System.out.println("sentences: " + countSentences(text)); // 5
System.out.println("paragraphs: " + countParagraphs(text)); // 2
System.out.println("reading min: " + readingTimeMin(countWords(text))); // 1
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →