编写一个程序,程序实现对用户指定的文本文件中的英文字符和字符串的个数进行统计功能
时间: 2024-02-25 21:53:31 浏览: 30
好的,以下是一个Java程序,它可以对指定的文本文件中的英文字符和字符串进行统计:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TextFileAnalyzer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 获取文件名
System.out.print("请输入文件名:");
String fileName = scanner.nextLine();
// 打开文件
File file = new File(fileName);
Scanner fileScanner;
try {
fileScanner = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("文件不存在!");
return;
}
// 统计字符和字符串个数
int charCount = 0;
int stringCount = 0;
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
charCount += line.replaceAll("\\s", "").length();
stringCount += line.split("\\s+").length;
}
// 输出结果
System.out.printf("文件中字符个数:%d\n", charCount);
System.out.printf("文件中字符串个数:%d\n", stringCount);
// 关闭文件
fileScanner.close();
}
}
```
该程序会首先要求用户输入要分析的文件名,然后打开文件并对其进行分析。程序会忽略文件中的空格、制表符和换行符,并统计文件中的字符和字符串个数。
你可以根据需要进行修改和扩展。