java - 在 .txt 文件中搜索字符串并获取 Java 中的行号和列号
问题描述
我目前遇到一个问题。我应该编写一个能够在作为参数给出的 .txt 文件中搜索字符串的程序。程序必须返回找到的字符串的行和列。我正在努力寻找实现这一目标的方法,并且不知道如何继续。我很高兴收到您的来信。
这是我处理我的任务的尝试: - 我考虑过通过缓冲读取器将文件的内容保存在字符串数组中,但这似乎不起作用,因为我无法从一开始就定义数组的长度 - 我还考虑通过缓冲读取器将文件内容保存在字符串中,然后将该字符串拆分为字符。但是我不确定我将如何能够检索原始文件中的行。
这是我目前拥有的非功能代码:
public class StringSearch{
public static void main(String[] args){
if(args.length > 0){
BufferedReader br = null;
String text = null;
try{
br = new BufferedReader(new FileReader(args[0]));
// attempt of saving the content of the "argument" file in a string array and then in a string
String[] lines = new String[]; // I know this does not work like this
for( int i = 0; i < lines.length; i++){
lines[i] = br.readLine;
text = text + lines[i];
i++;
}
text.split("\r\n");
} catch (IOException ioe){
ioe.printStackTrace();
} finally{
if (br != null) {
try{
br.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
}
}
}
}
解决方案
这是一种方法 -
- 让我们考虑一个计数器,它包含所有
readLine()
方法调用的计数器 - 表示 .txt 文件中的“行”。因此,在 while 循环中的每个 readLine 调用之后递增计数器。 - 接下来,在“”(空格)上分割该行以获取该行中每个单词的数组。然后,您可以遍历此数组并将单词与搜索字符串匹配。找到匹配时数组索引的位置将代表“列”。
推荐阅读
- .net - 为什么我不能在我的 .net Standard 2.0 库中使用“SupportedOSPlatform”属性?
- r - 根据元素而不是名称选择列
- .net - 使用 procdump 监听所有异常不起作用
- r - 使用 R 和爪子:如何使用配置文件中的配置文件设置凭据?
- git - git blame -L 使用 jgit 的行范围
- linux - 有没有办法配置 Docker 的嵌入式 DNS 服务器的上游名称服务器的端口?
- gatsby - 如何在不修改 html.js 的情况下将 Google Adsense 添加到 Gatsby 3+ 中的 gatsby-ssr.js?
- java - 如何使用流从列表列表中获取对象
- python - 根据最接近时间捕获的图像编写图像 GPS 元数据
- javascript - 将鼠标放在 WebdriverIO 中元素的特定位置