【问题标题】:Searching for a String in a .txt file and getting the row and column number in Java在 .txt 文件中搜索字符串并在 Java 中获取行号和列号
【发布时间】:2020-05-17 21:27:18
【问题描述】:

我目前遇到一个问题。我应该编写一个能够在作为参数给出的 .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();
                    }
                }


            }

        }
    }
}

【问题讨论】:

    标签: java arrays string search java-io


    【解决方案1】:

    这是一种方法 -

    1. 让我们考虑一个计数器,它为所有 readLine() 方法调用 - 表示 .txt 中的“行” 文件。因此,在每次调用 readLine 后递增计数器 while 循环。
    2. 接下来,拆分“”(空格)上的行以获取包含每个单词的数组 线。然后,您可以遍历此数组并将单词匹配到 搜索字符串。匹配时数组索引的位置 被发现将代表“列”。

    【讨论】:

    • 非常感谢您的回答。我仍然不清楚我应该首先对文本做什么。我应该读取行并将它们保存到字符串还是字符串数组中?什么是可取的?
    • 您可以动态解析文本。并且仅在找到匹配项时存储“行”和“列”值。如果有多个匹配项,您可以使用相关的数据结构来存储这些。
    【解决方案2】:

    你可以这样做:

    import java.io.File;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
            if (args.length != 2) {
                System.out.println("The correct syntax to use this program is: java Main <filename.txt> <text-to-search>");
                return;
            }
            Scanner scanner;
            File file = new File(args[0]);
            int rowCount = 1, index;
            String line;
    
            // Map to collect row and col info of the search string
            Map<String, String> lineColMap = new HashMap<String, String>();
    
            if (!file.exists()) {
                System.out.println("The file, " + args[0] + " does not exist");
                return;
            }
            try {
                scanner = new Scanner(file);
                while (scanner.hasNextLine()) {// Loop until the last line in the file
                    line = scanner.nextLine();// Read a line from the file
                    index = line.indexOf(args[1]);// Find if the string exists in the line
                    if (index != -1) {// If the string exists
                        // Put the row and col info of the search string into the map
                        lineColMap.put("Row: " + rowCount, "Column: " + index);
                    }
                    rowCount++;// Increase the row count
                }
            } catch (Exception e) {
                System.out.println("Error occured while processing the file");
                e.printStackTrace();
            }
            if (lineColMap.entrySet().size() > 0) {// If there is at least one entry collected into the map
                System.out.println("'" + args[1] + "' exists in " + args[0] + " as follows:");
                for (Map.Entry<String, String> entry : lineColMap.entrySet()) {
                    System.out.println(entry.getKey() + ", " + entry.getValue());
                }
            } else {
                System.out.println("'" + args[1] + "' does not exist in " + args[0]);
            }
        }
    }
    

    示例运行: java Main input.txt of

    'of' exists in input.txt as follows:
    Row: 1, Column: 51
    Row: 2, Column: 50
    Row: 3, Column: 50
    Row: 5, Column: 71
    

    input.txt的内容如下:

    Stack Overflow is a question and answer site for professional and enthusiast programmers.
    It is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky.
    It features questions and answers on a wide range of topics in computer programming.
    It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange.
    The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.
    

    代码中的逻辑是直截了当的,我相信你应该能够在第一次阅读时理解它。如有任何疑问,请随时发表评论。

    【讨论】:

    • 非常感谢您的意见和全面的帮助!选择一个 HashMap 来存储行号和列号是很巧妙的,但我不明白它是如何工作的。 HashMap 是为字符串声明的,但 rowCount 和 index 是整数,对吧?你能解释一下吗?提前非常感谢!
    • 我只将字符串存储到地图中,例如第一个条目是Row: 1=Column: 51,其中Row: 1 是键,Column: 51 是值;它们都是字符串。如果您只想存储数字(行号和列号),您可以将映射声明为Map&lt;Integer, Integer&gt; lineColMap = new HashMap&lt;Integer, Integer&gt;();,然后您可以使用lineColMap.put(rowCount, index); 将值存储到映射中。如有任何疑问,请随时发表评论。
    • 这是有道理的。再次感谢!关于 int rowCount 的最后一个问题。你像这样初始化它 int rowCount = 1, index;这是否意味着它具有两个值?
    • 不客气。 int rowCount = 1, index; 是在单个语句中声明两个或多个变量的快捷方式。您也可以将其写为int rowCount = 1; int index;,作为两个单独的语句。在这两种方式中的任何一种中,rowCount 将被初始化为 1index 将被初始化为 0(这是 int 变量的默认值)。如有任何疑问,请随时发表评论。
    猜你喜欢
    • 1970-01-01
    • 2011-09-03
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    相关资源
    最近更新 更多