Java Program To Count Words In A String
==========================================================================
import java.util.Scanner;
public class CountWordsInString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); System.out.println("Enter the String:"); String str = sc.nextLine();
int count = 1;
for (int i = 0; i < str.length() - 1; i++) { if ((str.charAt(i) == ' ') && (str.charAt(i + 1) != ' ')) { count++; } }
System.out.println("Number Of Words In A String:" + count);
}
}
Output:==============Enter the String:
Welcome To Java
Number Of Words In A String:3
Java Program To Count Words In A String
==========================================================================
import java.util.Scanner;
public class CountWordsInString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String str = sc.nextLine();
int count = 1;
for (int i = 0; i < str.length() - 1; i++) {
if ((str.charAt(i) == ' ') && (str.charAt(i + 1) != ' ')) {
count++;
}
}
System.out.println("Number Of Words In A String:" + count);
}
}
Comments
Post a Comment