Java程序计算字符串中的单词数
通过将所需的文件(对象)作为参数传递给其构造函数来创建FileInputStream 对象。使用 read()方法将文件的内容读取 到字节数组中。通过将字节数组传递给其构造函数来实例化String类。使用split()方法将String的单词读取到数组中。
创建一个整数变量,将其初始化为0,对于字符串数组的每个元素,intfor循环将增加计数。
示例
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<data.length; i++){
count++;
}
System.out.println("Number of characters in the given file are " +count);
}
}输出结果
Number of characters in the given String are 4
热门推荐
1 带清的简短祝福语
10 顾客简短祝福语大全集
11 男朋友新年祝福语简短
12 初八祝福语简短语
13 好听的元旦简短祝福语
14 离别简短的祝福语大全
15 结婚祝福语简短精辟 兄弟
16 发小结婚简短祝福语
17 女生成年祝福语简短
18 对离岗同事祝福语简短