2016-04-17 35 views
0

正如標題所示,我試圖解析文件,但忽略註釋(以#開頭)或空白行。我試圖爲此制定一個系統,但它似乎總是忽視它應該忽略註釋和/或空白行。解析文件,忽略註釋和空行

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] 

我在這裏的問題是,它依舊保持了「」和「#你好」的價值觀,這意味着什麼失敗了,我一直無法弄清楚。

那麼,我做錯了什麼,這保持不正確的價值觀?

回答

2

len(line) > 0對於"# Hello"行將爲真,因此它將被添加到output

目前,您正在添加的行不是以#開頭。您只需添加滿足以下兩個條件的行:

if !strings.HasPrefix(line, "#") && len(line) > 0 { 
    output[line] = true 
} 
+0

如果len(行)> 0 && line [0]!='#'{...} – OneOfOne