Java snippet to count number of words in a sentence
Java code snippet to count number of words in a sentence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
class countWords | |
{ | |
public static void main(String s[]) | |
{ | |
Scanner sc = new Scanner(System.in); | |
int count = 0; char ch; | |
System.out.println("Enter the sentence to count number of words : "); | |
String str = sc.nextLine(); | |
for(int i=0;i<str.length();i++) | |
{ | |
ch = str.charAt(i); | |
if(ch ==' ') count++; | |
} | |
System.out.println("The number of words in given string is : " + (count+1)); | |
} | |
} |
Comments
Post a Comment