-
Notifications
You must be signed in to change notification settings - Fork 1
/
CountNumberOfWordsInString.java
94 lines (76 loc) · 1.89 KB
/
CountNumberOfWordsInString.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.javamultiplex.string;
import java.util.Scanner;
public class CountNumberOfWordsInString {
public static void main(String[] args) {
Scanner input=null;
try
{
input=new Scanner(System.in);
System.out.println("Enter String: ");
String string=input.nextLine();
int words=0;
if(isOnlyOneWordString(string))
{
System.out.println("Number of word(s) : 1");
}
else
{
if(isMultipleSpacesExistBetweenWords(string))
{
string=getStringAfterRemovingMultipleSpacesBetweenWords(string);
}
words=getNumberOfWordsInString(string);
System.out.println("Number of word(s) : "+words);
}
}
finally
{
if(input!=null)
{
input.close();
}
}
}
private static int getNumberOfWordsInString(String string) {
String[] words=string.split("\\s");
int count=words.length;
return count;
}
private static String getStringAfterRemovingMultipleSpacesBetweenWords(
String string) {
int length=string.length();
StringBuffer newString=new StringBuffer();
for(int i=0;i<length;i++)
{
if(!(Character.isWhitespace(string.charAt(i))))
{
newString.append(string.charAt(i));
if((i+1)<length && Character.isWhitespace(string.charAt(i+1)))
{
newString.append(string.charAt(i+1));
}
}
}
return newString.toString();
}
private static boolean isMultipleSpacesExistBetweenWords(String string) {
String newString=string.trim();
String pattern="([\\S]+\\s{0,1})+";
boolean result=true;
if(newString.matches(pattern))
{
result=false;
}
return result;
}
private static boolean isOnlyOneWordString(String string) {
String newString=string.trim();
boolean result=false;
String pattern="^[\\S]+$";
if(newString.matches(pattern))
{
result=true;
}
return result;
}
}