dqd22496 2014-06-06 10:56
浏览 10
已采纳

去检查字符串中是否有字符串

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('
')
        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条回答 默认 最新

  • dtjpz48440 2014-06-06 11:53
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助