Translate

Monday, June 6, 2016

Write a program to count the number of words in a string without using library function.


package com.javahelp.stringprog;

import java.util.Scanner;

public class WordCount {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine(); // enter the string

int count;    // for counting the total word

if(s.charAt(0)==' ')
{
count=-1;
}
else
{
count=0;
}
for(int i=0; i<s.length(); i++)
{

if(i+1<s.length())
{

                //check space on index i and also check i+1 != sapce then increase count 1

                if(s.charAt(i)==' ' && s.charAt(i+1)!=' ')
{
count++;
}
}
}
System.out.println(count+1);
}
}


No comments:

Post a Comment