为了账号安全,请及时绑定邮箱和手机立即绑定

如何检查字符串中的变量是否为空白

如何检查字符串中的变量是否为空白

Go
人到中年有点甜 2022-10-24 16:20:08
想要达到我正在用 Go 构建一个应用程序。它是从 excel 文件创建一个 ruby 文件。如果xx中有值,我想把它放在数据中,如果它是空白的,我想跳过这个过程。但是,如果我如下所示输入 nil,则会出现错误。xx = xx + 19if row[xx] ! = nil {  data["IndustryId"] = row[xx];  }invalid operation: row[xx] != nil (mismatched types string and nil)我希望你能帮助我。代码测试.gofunc main() {  excel_file, err := excelize.OpenFile("./excel/data.xlsx")  if err != nil {    fmt.Println(err)    return  }  seeds := make([]string, 0, 1000)  seeds = append(seeds, "# Seed")  seeds = append(seeds, "# " + time.Now().Format("RFC3339"))  seeds = append(seeds, "")  tpl := template.Must(template.ParseFiles(`test.tmpl`))  rows, err := excel_file.GetRows("Test")  for i, row := range rows {    if i != 0 {      xx := 2      data := map[string]string{        "Id": row[xx],      }      xx = xx + 19      if row[xx] != nil {        data["IndustryId"] = row[xx];      }      if err := tpl.Execute(&output, data); err != nil {        fmt.Println(err)        return      }      seeds = append(seeds, output.String())    }  }  export_file("./seeds/import_test.rb", seeds)}
查看完整描述

2 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

rows, err := excel_file.GetRows("Test")

rows是类型[][]string。现在当你这样做时:

for i, row := range rows { ... }

row是的[]string,现在如果你索引它,你会得到一个字符串。

字符串的零值是""(空字符串) 而不是nil。因此,请将其与""而不是进行比较nil。这里:

row[xx] != ""


查看完整回答
反对 回复 2022-10-24
?
波斯汪

TA贡献1811条经验 获得超4个赞

您应该 Trim row[xx] 以确保该行不只包含空格并将其与“”而不是 nil 进行比较。


import strings 

....

strings.TrimSpace(row[xx]) != "" 


查看完整回答
反对 回复 2022-10-24
  • 2 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号