Поиск строки в текстовом файле и получение номера строки и столбца в Java - PullRequest
3 голосов
/ 01 февраля 2020

Я в настоящее время застрял с проблемой. Я должен написать программу, которая может искать строку в файле .txt, заданном в качестве аргумента. Программа должна вернуть строку и столбец найденной строки. Я изо всех сил пытаюсь найти способ достигнуть этого и понятия не имею, как go дальше. Я был бы очень рад услышать от вас.

Вот моя попытка решить мою задачу: - Я думал о сохранении содержимого файла с помощью буферизованного читателя в строковом массиве, но это не похоже работать, так как я не могу определить длину массива с самого начала - я также думал о сохранении содержимого файла с помощью буферизованного читателя в строке, а затем разбить эту строку на символы. Однако я не уверен, каким образом я смогу получить строки в исходном файле.

Это неработающий код, который у меня есть на данный момент:

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();
                    }
                }


            }

        }
    }
}

Ответы [ 2 ]

1 голос
/ 01 февраля 2020

Вы можете сделать это следующим образом:

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.

Лог c в коде прост, и я считаю, что вы должны быть в состоянии понять это в первом чтении. Не стесняйтесь комментировать в случае каких-либо сомнений.

1 голос
/ 01 февраля 2020

Вот один подход -

  1. Давайте рассмотрим счетчик, который содержит счетчик для всех вызовов метода readLine() - представляющий «строку» в файле .txt. Так, увеличивайте счетчик после каждого вызова readLine в то время как l oop.
  2. Далее, разделите строку на "" (пробел), чтобы получить массив каждого слова в строке. Затем вы можете перебрать этот массив и сопоставить слово со строкой поиска. Позиция индекса массива в момент обнаружения совпадения будет представлять «столбец».
...