【一起学数据结构与算法分析】第五篇:处理include标签

处理include标签其实第一章的习题部分,因为篇幅过大所有决定单独开一章节。

题目要求如下:
在这里插入图片描述
既然第一章学了递归,那我们不妨也用递归的方式来处理解决。

大体逻辑其实很简单,就是逐行读文件内容,遇到#include标签则递归处理被引入的文件名。

在这里插入图片描述
核心代码如下。

/**
     * Process file's include recursively.
     * @return file content with included file's content.
     */
    private fun processFile(filename: String): String {
        // If file is invalid, that is not in valid files.
        if(filename !in INVALID_FILES) {
            throw IllegalArgumentException("file not valid with name $filename")
        }
        // If file not exists, print error message and throw an exception.
        val file = File(FILE_DIRECTORY, filename)
        if(!file.exists()) {
            throw FileNotFoundException("file not foud with path $file")
        }
        // Read file content and process referenced file if needed.
        val fileReader = BufferedReader(InputStreamReader(file.inputStream(), StandardCharsets.UTF_8))
        val fileContent = StringBuilder()
        while (true) {
            val line = fileReader.readLine() ?: break
            // Hit include keyword!!!
            if(line.matches(KEYWORD_REGEX.toRegex())) {
                // Get filename after the include.
                val includeFileName = getFileName(line)
                // File is not self-referential.
                if(includeFileName.isNotEmpty() && includeFileName != filename) {
                    fileContent.append(processFile(includeFileName)).append("\n")
                }
            } else {
                fileContent.append(line).append("\n")
            }
        }
        // Simply close
        fileReader.close()
        return fileContent.toString()
    }

最后我们建4个文件来演示下,其中四个文件的引用关系如下:
在这里插入图片描述
随便加些内容,可以看到,结果已经正常显示 :
在这里插入图片描述
其中file2引用自身无效,在代码中已处理。

当然了,在实际应用中不应该用递归来实现,因为每次递归都打开了一个文件流,如果递归的深度很大,是非常消耗性能的。

git:https://github.com/codersth/dsa-study
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Meta章磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值