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

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

Go check if string in slices of string

问题

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

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

package main

import (
    "bufio"
    "fmt"
    "os"
    "os/exec"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    foundfdb := false
    fdbslices := []string{"f", "d", "b", "files", "directories", "both"}

    for {
        fmt.Print("Files, Directories, or Both: ")
        fdb, _ := reader.ReadString('\n')
        fdb = strings.ToLower(fdb)
        for i := range fdbslices {
            if strings.ContainsAny(fdbslices[i], fdb) {
                foundfdb = true
            }
        }
        if foundfdb = true {
            break
        }
    }
}

似乎 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

package main

import (
    "bufio"
    "fmt"
    "os"
    "os/exec"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    foundfdb := false
    fdbslices := []string{"f", "d", "b", "files", "directories", "both"}

    for {
        fmt.Print("Files, Directories, or Both: ")
        fdb, _ := reader.ReadString('\n')
        fdb = strings.ToLower(fdb)
        for i := range fdbslices {
            if strings.ContainsAny(fdbslices[i], fdb) {
                foundfdb = true
            }
        }
        if foundfdb = true {
            break
        }
    }
}

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

func InArray(a []string, e string) bool {
    for _, x := range a {
        if x == e {
            return true
        }
    }
    return false
}
英文:

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:

func InArray(a []string, e string) bool {
    for _, x := range a {
        if x == e {
            return true
        }
    }
    return false
}

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:

确定