mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-08 10:15:51 +08:00
Counting the number of words in string
This commit is contained in:
@ -1,23 +1,19 @@
|
|||||||
|
import java.util.Scanner;
|
||||||
class CountTheWords
|
class CountTheWords
|
||||||
{
|
{
|
||||||
public static void main(String[] args)
|
public static void main(String args[])
|
||||||
{
|
{
|
||||||
System.out.println("Enter the string");
|
System.out.println("Enter the string");
|
||||||
|
|
||||||
Scanner sc = new Scanner(System.in);
|
Scanner sc = new Scanner(System.in);
|
||||||
|
|
||||||
String s=sc.nextLine();
|
String s=sc.nextLine();
|
||||||
|
int count = 1;
|
||||||
int count = 1;
|
for (int i = 0; i < s.length()-1; i++)
|
||||||
|
|
||||||
for (int i = 0; i < s.length()-1; i++)
|
|
||||||
{
|
{
|
||||||
if((s.charAt(i) == ' ') && (s.charAt(i+1) != ' '))
|
if((s.charAt(i) == ' ') && (s.charAt(i+1) != ' '))
|
||||||
{
|
{
|
||||||
count++;
|
count++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
System.out.println("Number of words in the string = "+count);
|
||||||
System.out.println("Number of words in a string = "+count);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
Reference in New Issue
Block a user