java统计文本中英文单词个数split_如何使用Java计算文本文件中的单词数?
读取文本文件中的单词数通过将所需的文件(对象)作为参数传递给其构造函数来创建FileInputStream对象。使用read()方法将文件的内容读取到字节数组中。通过将字节数组传递给其构造函数来使String类满意。使用split()方法将String的单词读取到数组中。创建一个整数变量,将其初始化为0,对于字符串数组的每个元素,int for循环将增加计数。示例importjava.io.Fi.
读取文本文件中的单词数通过将所需的文件(对象)作为参数传递给其构造函数来创建FileInputStream对象。
使用read()方法将文件的内容读取到字节数组中。
通过将字节数组传递给其构造函数来使String类满意。
使用split()方法将String的单词读取到数组中。
创建一个整数变量,将其初始化为0,对于字符串数组的每个元素,int for循环将增加计数。
示例import java.io.File;
import java.io.FileInputStream;
public class Sample {
public static void main(String args[]) throws Exception{
int count =0;
File file = new File("data");
FileInputStream fis = new FileInputStream(file);
byte[] bytesArray = new byte[(int)file.length()];
fis.read(bytesArray);
String s = new String(bytesArray);
String [] data = s.split(" ");
for (int i=0; i
count++;
}
System.out.println("Number of characters in the given file are " +count);
}
}
输出结果Number of characters in the given String are 4
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)