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

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

Golang use LIKE inside IF statement best practice

问题

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

s1 := "lorem ipsum"
sum := 0

for _, v := range s1 {
    if string(v) like ("a", "i", "u", "e", "o") {
        sum += 1
    }
}

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

package main

import (
	"fmt"
	"strings"
)

func main() {
	s1 := "lorem ipsum"
	sum := 0

	for _, v := range s1 {
		if strings.ContainsAny(string(v), "aiueo") {
			sum += 1
		}
	}

	fmt.Println(sum)
}

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

英文:

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

s1  := "lorem ipsum"
sum := 0

for _, v := range s1 {

		if string(v) like ("a","i","u","e","o") {
			sum+=1
		}

}

答案1

得分: 2

你可以使用switch语句。

switch支持多个匹配项。

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

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

英文:

You can use switch statement.

Switch supports multiple matches

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

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:

确定