当文件有多个空格时,如何计算文件中的单词数JAVA
我尝试在linux中实现命令“wc file name”的功能。 此命令统计以下各项的数量:当文件有多个空格时,如何计算文件中的单词数JAVA,java,Java,我尝试在linux中实现命令“wc file name”的功能。 此命令统计以下各项的数量: 线条 言语 字节 在一个文件中 这是我的密码: public class wc { public static void main(String[] args) throws IOException { //counters int charsCount = 0; int wordsCount = 0; int linesCount = 0; Sca
- 线条
- 言语
- 字节
public class wc {
public static void main(String[] args) throws IOException {
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner in = null;
try(Scanner scanner = new Scanner(new BufferedReader(new FileReader(new File("Sample.txt"))))){
File file = new File("Sample.txt");
while (scanner.hasNextLine()) {
String tmpStr = scanner.nextLine();
if (!tmpStr.equalsIgnoreCase("")) {
String replaceAll = tmpStr.replaceAll("\\s+", "");
charsCount += replaceAll.length();
wordsCount += tmpStr.split(" ").length;
}
++linesCount;
}
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
System.out.println("# of bytes: " + file.length());
}
}
}
问题是文件中有如下文本:
Hex Description Hex Description
20 SPACE
21 EXCLAMATION MARK A1 INVERTED EXCLAMATION MARK
22 QUOTATION MARK A2 CENT SIGN
23 NUMBER SIGN A3 POUND SIGN
有多个具有不同长度的空间。有时加倍,有时甚至更多。如何重构我的代码,以便能够正确计算字数?如何去掉多个空格?接受正则表达式,因此您可以简单地在\\s+
上拆分(多个空格):
输出:
7 words
请参阅。
split
也需要一个正则表达式,因此这应该可以工作:
tmpStr.split("\\s+")
@马文已经在这里提出了解决方案 这是分割具有多个空格的字符串的另一种方法 s、 拆分(“[]+”) 对你来说也应该很好 范例
String s="This is my test file.";
String s1[]=s.split("[ ]+");
System.out.println(s1.length);
输出:-
5
我通过创建tmpStr使用该方法,用空字符串替换所有相乘的空格。该死的为什么我没注意到。。。?
5