Java program to count number of words in given string


Program

public class WordCount
{
public static void main(String args[])
{
String s = "welcome to candid java tutorial";

int count = 1;

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

}
}
System.out.println("Number of words in a string = " + count);
}
}

Output

Number of words in a string = 5




Related Post

Comments

VInay sharma
         i want to count words from this string ...Help me !! String w = " i am not a robot . " between i and am : 1 space between not and a : 4 spaces between a and robot : 3 spaces.
VIKASH KUMAR SAW
         package com.AllCoreJavaInterviewQuestionPractise; public class TestNoOfWords { public static void main(String[] args) { String s = "I Love my Country"; System.out.println(s.trim().split(" ").length); } }
sunita
         Java program to count number of words in given string using recursion ?
Roshni B
         Count the even no position in: This is my bag Output: This My

©candidjava.com