检查字符串是否在字符串切片中。

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

Go check if string in slices of string

问题

作为前言,我来自Python,我会使用一个包含值的列表,而不是字符串切片,并使用 "if x in list"。请告诉我我是否做错了。

我需要从用户那里获取输入,如果它包含在我的切片字符串中,那么就跳出循环并继续执行,否则再次提示用户。现在我有这个代码:

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "strings"
  8. )
  9. func main() {
  10. reader := bufio.NewReader(os.Stdin)
  11. foundfdb := false
  12. fdbslices := []string{"f", "d", "b", "files", "directories", "both"}
  13. for {
  14. fmt.Print("Files, Directories, or Both: ")
  15. fdb, _ := reader.ReadString('\n')
  16. fdb = strings.ToLower(fdb)
  17. for i := range fdbslices {
  18. if strings.ContainsAny(fdbslices[i], fdb) {
  19. foundfdb = true
  20. }
  21. }
  22. if foundfdb = true {
  23. break
  24. }
  25. }
  26. }

似乎 ContainsAny() 给了我一些错误的结果。肯定有更简单的方法来做到这一点,或者有吗?

英文:

As a preface I'm coming from python, where I would have a list with my values instead of string slices and do "if x in list". Please tell me if I'm doing this wrong.

I need to take input from the user, if it's contained in my sliced string then break out of my loop and continue, otherwise prompt the user again. Right now I have this

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "strings"
  8. )
  9. func main() {
  10. reader := bufio.NewReader(os.Stdin)
  11. foundfdb := false
  12. fdbslices := []string{"f", "d", "b", "files", "directories", "both"}
  13. for {
  14. fmt.Print("Files, Directories, or Both: ")
  15. fdb, _ := reader.ReadString('\n')
  16. fdb = strings.ToLower(fdb)
  17. for i := range fdbslices {
  18. if strings.ContainsAny(fdbslices[i], fdb) {
  19. foundfdb = true
  20. }
  21. }
  22. if foundfdb = true {
  23. break
  24. }
  25. }
  26. }

It seems ContainsAny() is giving me some false positives. There's got to be an easier way to do this, or is there?

答案1

得分: 4

ContainsAny允许你查找一个特定的字符是否在一个特定的字符串中,我不认为这是你想要的。对于我的一个项目,我实现了一个函数来在一个切片中查找一个字符串:

  1. func InArray(a []string, e string) bool {
  2. for _, x := range a {
  3. if x == e {
  4. return true
  5. }
  6. }
  7. return false
  8. }
英文:

ContainsAny allows you to look for a specific character is in a specific string, and I do not think that's what you want. For one of my projects, I implemented a function to look for a string in a slice:

  1. func InArray(a []string, e string) bool {
  2. for _, x := range a {
  3. if x == e {
  4. return true
  5. }
  6. }
  7. return false
  8. }

huangapple
  • 本文由 发表于 2014年6月6日 18:56:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/24080147.html
匿名

发表评论

匿名网友

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

确定