From df20459b6c8258ce1e7985ff0ef8e97f35c4617b Mon Sep 17 00:00:00 2001 From: Ashish Agarwal Date: Sun, 9 Apr 2017 10:26:56 +0530 Subject: [PATCH] Counting the number of words in string --- countwords.java | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/countwords.java b/countwords.java index 78f6eb2b..a1d4d72d 100644 --- a/countwords.java +++ b/countwords.java @@ -1,23 +1,19 @@ +import java.util.Scanner; class CountTheWords { - public static void main(String[] args) + public static void main(String args[]) { System.out.println("Enter the string"); - Scanner sc = new Scanner(System.in); - String s=sc.nextLine(); - - int count = 1; - - for (int i = 0; i < s.length()-1; i++) + int count = 1; + for (int i = 0; i < s.length()-1; i++) { if((s.charAt(i) == ' ') && (s.charAt(i+1) != ' ')) { - count++; + count++; } } - - System.out.println("Number of words in a string = "+count); + System.out.println("Number of words in the string = "+count); } } \ No newline at end of file