检查数组包含一个值 [英] Check if an array contains a value

查看:135
本文介绍了检查数组包含一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在猛砸,什么是测试如果数组包含特定值的最简单方法?

In Bash, what is the simplest way to test if an array contains a certain value?

修改:从答案和注释的帮助下,一些测试后,我想出了这一点:

EDIT: with help from the answers and the comments, after some testing, I came up with this:

function contains() {
    local n=$#
    local value=${!n}
    for ((i=1;i < $#;i++)) {
        if [ "${!i}" == "${value}" ]; then
            echo "y"
            return 0
        fi
    }
    echo "n"
    return 1
}

A=("one" "two" "three four")
if [ $(contains "${A[@]}" "one") == "y" ]; then
    echo "contains one"
fi
if [ $(contains "${A[@]}" "three") == "y" ]; then
    echo "contains three"
fi

我不知道这是否是最好的解决办法,但它似乎工作。

I'm not sure if it's the best solution, but it seems to work.

推荐答案

code这显示了如何从一个数组替换子。您可以在阵列的副本,并尝试从副本中删除目标值。如果复制和原来有那么不同,那么目标值存在于原始字符串。

There is sample code that shows how to replace a substring from an array. You can make a copy of the array and try to remove the target value from the copy. If the copy and original are then different, then the target value exists in the original string.

的直接的(但可能更费时)的解决方案是简单地通过整个阵列迭代地和单独检查每个项目。这是我做的一般,因为它很容易实现,你可以在一个功能包(见在将数组传递给函数)这个信息。

The straightforward (but potentially more time-consuming) solution is to simply iterate through the entire array and check each item individually. This is what I typically do because it is easy to implement and you can wrap it in a function (see this info on passing an array to a function).

这篇关于检查数组包含一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆