mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 00:54:32 +08:00
Counting words of a string
This commit is contained in:
23
countwords.java
Normal file
23
countwords.java
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
class CountTheWords
|
||||||
|
{
|
||||||
|
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++)
|
||||||
|
{
|
||||||
|
if((s.charAt(i) == ' ') && (s.charAt(i+1) != ' '))
|
||||||
|
{
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("Number of words in a string = "+count);
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user