简体   繁体   English

使用扫描仪Java仅计数文件中的单词

[英]Counting for only words in a file using a scanner Java

I am trying to get into java and i am stuck on a problem which is to count only words in a java file using a scanner 我正在尝试进入Java,但我陷入了一个问题,该问题是使用扫描仪仅计数Java文件中的单词

while (sc.hasNextLine()) {
 sc.next(); 

 count++; } 

and this is the answer to most of the questions i have seen although this counts everything including numbers punctuation etc. 这是我见过的大多数问题的答案,尽管这很重要,包括数字标点符号等。

So what is the best approach to check for words only ? 那么,仅检查单词的最佳方法是什么?

You could keep your original code, and them match it with (allows apostrophes but doesn't allow apostrophes at the start) 您可以保留原始代码,并与它们匹配(允许使用撇号,但一开始不允许使用撇号)

if (word.matches("[a-zA-Z']+") && !word.matches("'")) {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM