FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Others/CountWords.java at master · primary-code-test/Java · GitHub
primary-code-test
Java
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
Others
/
CountWords.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
44 lines (38 loc) · 1.26 KB
Breadcrumbs
Java
/
Others
/
CountWords.java
Copy path
File metadata and controls
44 lines (38 loc) · 1.26 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package
Others
;
import
java
.
util
.
Scanner
;
/**
* You enter a string into this program, and it will return how many words were in that particular
* string
*
* @author Marcus
*/
public
class
CountWords
{
public
static
void
main
(
String
[]
args
) {
Scanner
input
=
new
Scanner
(
System
.
in
);
System
.
out
.
println
(
"Enter your text: "
);
String
str
=
input
.
nextLine
();
System
.
out
.
println
(
"Your text has "
+
wordCount
(
str
) +
" word(s)"
);
System
.
out
.
println
(
"Your text has "
+
secondaryWordCount
(
str
) +
" word(s)"
);
input
.
close
();
}
private
static
int
wordCount
(
String
s
) {
if
(
s
==
null
||
s
.
isEmpty
())
return
0
;
return
s
.
trim
().
split
(
"[
\\
s]+"
).
length
;
}
/**
* counts the number of words in a sentence but ignores all potential non-alphanumeric characters
* that do not represent a word. runs in O(n) where n is the length of s
*
* @param s String: sentence with word(s)
* @return int: number of words
*/
private
static
int
secondaryWordCount
(
String
s
) {
if
(
s
==
null
||
s
.
isEmpty
())
return
0
;
StringBuilder
sb
=
new
StringBuilder
();
for
(
char
c
:
s
.
toCharArray
()) {
if
(
Character
.
isLetter
(
c
) ||
Character
.
isDigit
(
c
))
sb
.
append
(
c
);
}
s
=
sb
.
toString
();
return
s
.
trim
().
split
(
"[
\\
s]+"
).
length
;
}
}
Back
|
FazBrowse Home
|
New Git URL