java - 删除文本文件中的空格
问题描述
我必须编写一个简单的代码来计算文本文件中的单词。然后有人告诉我,这是不完整的,因为例如,当连续有 2 个或更多空格时,函数会将它们计为一个单词,结果将不正确。所以我试图通过制作一个列表并删除那里的所有“”元素来修复它,但它似乎不起作用。你能建议可以做什么吗?
这是现在的代码:
int count = 0;
File file = new File("C:\\Users\\user\\Desktop\\Test.txt");
FileInputStream fis = new FileInputStream(file);
byte[] bytesArray = new byte[(int) file.length()];
fis.read(bytesArray);
String s = new String(bytesArray);
String[] data = s.split(" ");
List<String> list = new ArrayList<>(Arrays.asList(data));
list.remove(" ");
data = list.toArray(new String[0]);
for (int i = 0; i < data.length; i++) {
count++;
}
System.out.println("Number of words in the file are " + count);
解决方案
您可以通过正则表达式实现这一点
字符串[] 数据 = s.split("\s+");
int count = 0;
File file = new File("/home/vahid/Documents/test.txt");
FileInputStream fis = new FileInputStream(file);
byte[] bytesArray = new byte[(int) file.length()];
fis.read(bytesArray);
String s = new String(bytesArray);
String[] data = s.split("\\s+");
List<String> list = new ArrayList<>(Arrays.asList(data));
list.remove(" ");
data = list.toArray(new String[0]);
for (int i = 0; i < data.length; i++) {
count++;
}
System.out.println("Number of words in the file are " + count);
推荐阅读
- python - 使用 Selenium 进行网页抓取,抓取子页面的问题
- adaptive-bitrate - Youtube 或 Instagram 等在线视频服务如何自动更改其视频分辨率?
- html - Django 应用程序错误中的 Reportlab - 禁止(CSRF 令牌丢失或不正确。)
- aws-sdk - S3Exception 与 SdkException
- python - 计算 DataFrame 中出现次数并将它们移动到列的最佳方法是什么?
- python - 我希望下拉选项是使用 Flask 在我的数据库中注册的选项
- reactjs - React, Rechart中从不同数据源中排序X轴标签
- oracle - ORA-00947: 值不足
- flutter - NoSuchMethodError 在 null 上调用了方法“[]”
- sabre - 座位图 (Bet)a 4.0.0 - 所有座位显示“SeatIsFree”