java - 如何搜索分成两行的单词?

标签 java logic

我正在用java编写一个程序来搜索.txt文件中的单词列表(交易编号)。 .txt 文件可以有任意行数。

List<String> transactionList = new ArrayList<String>(
            Arrays.asList("JQ7P00049", "TM7P04797", "RT6P70037");
FileReader fileReader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(fileReader);
        try {
            String readLine = bufferedReader.readLine();
            for (String transactionIndex : transactionList) {
                if (readLine != null) {
                    if (readLine.contains(transactionIndex)) {
                        System.out.println(transactionIndex + ": true");
                        readLine = bufferedReader.readLine();
                    } else {
                        readLine = bufferedReader.readLine();
                    }
                }
            }
        }

程序运行良好,除非单词被分成两行,例如:

-------- JQ7P0
第0049章----------

这显然是因为 bufferedReader 逐行读取并将搜索字符串与该行中存在的内容进行比较。

有什么办法可以处理这种情况吗?

最佳答案

正如 durron597 提到的,您没有循环遍历整个文件,但这里有一个解决方案,假设该文件至少有 2 行,并且事务字符串的长度不超过 2 行。

它将每一行与下一行连接起来,并在连接的行中搜索字符串。为了防止同一笔交易被打印两次,我添加了额外的检查。

    List<String> transactionList = new ArrayList<String>( Arrays.asList("JQ7P00049", "TM7P04797", "RT6P70037") );
    FileReader fileReader = new FileReader(filePath);
    BufferedReader bufferedReader = new BufferedReader(fileReader);
    try {
        // Search the first line
        String lastLine = bufferedReader.readLine();
        for (String transactionIndex : transactionList) {
            if (lastLine.contains(transactionIndex)) {
                System.out.println(transactionIndex + ": true");
            } 
        }
        String currentLine = null;

        // Search the remaining lines
        while((currentLine=bufferedReader.readLine()) != null) {
            String combined = lastLine + currentLine;
            for (String transactionIndex : transactionList) {
                if (currentLine.contains(transactionIndex) || (!lastLine.contains(transactionIndex) && combined.contains(transactionIndex))) {
                    System.out.println(transactionIndex + ": true");
                } 
            }
            lastLine = currentLine;
        }

    } catch ( Exception e ) {
        System.out.println( e.getClass().getSimpleName() + ": " + e.getMessage() );
    } finally {
        bufferedReader.close();
    }

关于java - 如何搜索分成两行的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144200/

相关文章:

logic - 将业务规则与业务逻辑分离

c++ - 我的逻辑让我失望(C++、nslookup、字符比较)

javascript - 检查重复事件是否在当前日期到期

java - Android Studio NDK 解决方法

Java boolean 返回 if 语句

java - Spring3.1 CORS。这段代码是什么意思?我不明白为什么作者使用 'semi-colon' 到那个位置

java - 使用 Quartz 库,如何从数据库表中读取 cron 表达式,而不是从属性文件中获取

python - 评估一阶算术公式

java - hibernate :PSQLException:错误:列 “this_.user_id” 不存在

java - 设置特殊正则表达式的长度