在这个Java代码中,文件的每个句子中有多少个单词
我需要计算在这个代码中文件的每个句子中有多少个单词 我们有一个名为archivo的文件:在这个Java代码中,文件的每个句子中有多少个单词,java,file,Java,File,我需要计算在这个代码中文件的每个句子中有多少个单词 我们有一个名为archivo的文件: File archivo = null; try { archivo = new File("Text.txt"); String line; FileReader fr = new FileReader (archivo); BufferedReader br = new BufferedReader(fr); int i,a=0; whi
File archivo = null;
try {
archivo = new File("Text.txt");
String line;
FileReader fr = new FileReader (archivo);
BufferedReader br = new BufferedReader(fr);
int i,a=0;
while((linea=br.readLine())!=null) {
for(i=0;i<line.length();i++){
if(i==0){
if(line.charAt(i)!=' ')
a++;
}else{
if(line.charAt(i-1)==' ')
if(line.charAt(i)!=' ')
a++;
}
}
}
text.txt说:
嗨
我是凯蒂
我有两只猫。按如下方式操作:
String line;
int count=0, totalCount=0;
while((line=br.readLine())!=null) {
count = line.split("\\s+").length;
System.out.println("The number of words in '" + line + "' is: " + count);
totalCount += count;
}
System.out.println("The total number of words in the file is " + count);
解释:函数根据指定的正则表达式将字符串拆分为字符串数组。正则表达式,\\s+
表示一个或多个空格。对于每一行,程序都会打印count
,即字数(即拆分后生成数组的长度),并将其添加到totalCount
。最后,程序打印totalCount
(文件中的总字数) 按以下步骤操作:
String line;
int count=0, totalCount=0;
while((line=br.readLine())!=null) {
count = line.split("\\s+").length;
System.out.println("The number of words in '" + line + "' is: " + count);
totalCount += count;
}
System.out.println("The total number of words in the file is " + count);
解释:函数根据指定的正则表达式将字符串拆分为字符串数组。正则表达式,
\\s+
表示一个或多个空格。对于每一行,程序都会打印count
,即字数(即拆分后生成数组的长度),并将其添加到totalCount
。最后,程序打印totalCount
(文件中的总字数) 那么输出是什么呢?它必须是每个句子的字数,比如“我们在第一行有5个单词,在第二行有2个,…”你在说句子的字数你在说一行的字数,一行不等于一个句子你忘了提到一些重要的事情,比如“每行只包含一个句子”吗那么输出是什么呢?它必须是每个句子的字数,比如“我们在第一行有5个单词,在第二行有2个,…”你在说句子的字数你在说一行的字数,一行不等于一个句子你忘了提一些重要的事情,比如“每行只包含一个句子”吗?