解析文件,忽略注释和空行

正如标题所说,我正在尝试解析文件但忽略注释(以 开头#)或空行。我试图为此创建一个系统,但它似乎总是忽略它应该忽略注释和/或空行。


lines := strings.Split(d, "\n")

var output map[string]bool = make(map[string]bool)


for _, line := range lines {

    if strings.HasPrefix(line, "#") != true {

        output[line] = true

    } else if len(line) > 0 {

        output[line] = true

    }

}

运行时(这是函数的一部分),它输出以下内容


This is the input ('d' variable):

Minecraft

Zerg Rush

Pokemon


# Hello


This is the output when printed ('output' variable):


map[Minecraft:true Zerg Rush:true Pokemon:true :true # Hello:true]

我的问题是它仍然保留了 "" 和 "#Hello" 值,这意味着某些事情失败了,我无法弄清楚的事情。


那么,我做错了什么,这保留了不正确的价值观?


慕尼黑8549860
浏览 155回答 1
1回答

千万里不及你

len(line) > 0该行将是 true "# Hello",因此它将被添加到output.目前,您正在添加不以 # 开头或不为空的行。您只需要添加满足两个条件的行:if !strings.HasPrefix(line, "#") && len(line) > 0 {    output[line] = true}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go