Golang在IF语句中使用LIKE的最佳实践

huangapple go评论97阅读模式
英文:

Golang use LIKE inside IF statement best practice

问题

如果我有很多选项需要在IF语句中进行筛选,我可以使用类似这样的函数吗?

  1. s1 := "lorem ipsum"
  2. sum := 0
  3. for _, v := range s1 {
  4. if string(v) like ("a", "i", "u", "e", "o") {
  5. sum += 1
  6. }
  7. }

如果你想在Go语言中实现这样的功能,可以使用strings.ContainsAny函数来检查一个字符串是否包含指定的字符。你可以将要筛选的字符放在一个字符串中,然后使用strings.ContainsAny函数来判断字符是否在该字符串中出现。下面是一个示例代码:

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. func main() {
  7. s1 := "lorem ipsum"
  8. sum := 0
  9. for _, v := range s1 {
  10. if strings.ContainsAny(string(v), "aiueo") {
  11. sum += 1
  12. }
  13. }
  14. fmt.Println(sum)
  15. }

这段代码会输出符合条件的字符的数量。在这个例子中,字符"a"、"i"、"u"、"e"、"o"会被认为是符合条件的字符。

英文:

if i have many option to be filter in IF statement, can i use some function like this?

  1. s1 := "lorem ipsum"
  2. sum := 0
  3. for _, v := range s1 {
  4. if string(v) like ("a","i","u","e","o") {
  5. sum+=1
  6. }
  7. }

答案1

得分: 2

你可以使用switch语句。

switch支持多个匹配项。

  1. switch string(v) {
  2. case "a","i","u","e","o":
  3. sum+=1
  4. }

在playground中尝试一下 - https://play.golang.org/p/QRYhEDA7EUZ

英文:

You can use switch statement.

Switch supports multiple matches

  1. switch string(v) {
  2. case "a","i","u","e","o":
  3. sum+=1
  4. }

Tried it in the playground - https://play.golang.org/p/QRYhEDA7EUZ

huangapple
  • 本文由 发表于 2021年10月12日 00:31:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/69529603.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定