From a0e3c349f2c6d945edaefe4a218ea0789cc59af5 Mon Sep 17 00:00:00 2001 From: Aayush-Vats <56789473+Aayush-Vats@users.noreply.github.com> Date: Sun, 20 Oct 2019 20:15:21 +0530 Subject: [PATCH] Finding number of characters in a string. --- Characters | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Characters diff --git a/Characters b/Characters new file mode 100644 index 0000000..7734e17 --- /dev/null +++ b/Characters @@ -0,0 +1,20 @@ +public class CountNumberOfWordsInString { + + public static void main(String[] args) { + + countNumberOfWords("My name is Pankaj"); + countNumberOfWords("I Love Java Programming"); + countNumberOfWords(" This is not properly formatted line "); + + } + + private static void countNumberOfWords(String line) { + //System.out.println(line.split(" ").length); //won't work with tabs and multiple spaces + + String trimmedLine = line.trim(); + int count = trimmedLine.isEmpty() ? 0 : trimmedLine.split("\\s+").length; + + System.out.println(count); + } + +}