package main
import "fmt"
//查询函数
func search(arr []string, target string) (targetIndex []int) {
count := 0
for i := 0; i < len(arr); i++ {
if arr[i] == target {
targetIndex = append(targetIndex, i)
count++
}
}
if count == 0 {
fmt.Printf("数组中没有'%s'\n", target) //%s 直接输出字符串或者[]byte
} else {
fmt.Printf("'%s'在数组中有%d个\n", target, count)
}
return targetIndex
}
func main() {
var arr = []string{"AA", "BB", "CC", "DD", "AA"}
var target string
fmt.Print("输入要查询的字母:")
fmt.Scanln(&target)
fmt.Printf("元素对应的下标为:%v\n", search(arr, target))
}
输出结果:
新手,有问题还请评论区指教!