-
Notifications
You must be signed in to change notification settings - Fork 95
/
StringEachWordCount.java
47 lines (41 loc) · 993 Bytes
/
StringEachWordCount.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Scanner;
public class StringEachWordCount {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter any sentance");
String s = sc.nextLine();
System.out.println("Number of Words in given string is "+WordCount(s));
System.out.println("Number of Words in given string is "+Word_Count(s));
System.out.println("Number of Words in given string is "+Word_CountE(s));
}
public static int WordCount(String s) {
int w_count=1;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)==' ')
{
w_count++;
}
}
return w_count ;
}
//using Recursion
public static int Word_Count(String s)
{
return s.split(" ").length;
}
//WHEN EXTRA SPACE IN STRING
public static int Word_CountE(String s)
{
int W_Count=0;
String str[]=s.split(" ");
for(String word:str)
{
if(word.trim().length()>0)
{
W_Count++;
}
}
return W_Count;
}
}