如何检查一个字符串是否在数组中没有遍历元素呢? [英] How can I check if a string is in an array without iterating over the elements?

查看:169
本文介绍了如何检查一个字符串是否在数组中没有遍历元素呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有检查,如果在一个字符串数组存在字符串的方式 - 不通过遍历数组

Is there a way of checking if a string exists in an array of strings - without iterating through the array?

例如,下面给出的剧本,我怎么能正确地执行它来测试存储在变量$测试值在$数组存在?

For example, given the script below, how I can correctly implement it to test if the value stored in variable $test exists in $array?

array=('hello' 'world' 'my' 'name' 'is' 'perseus')

#pseudo code
$test='henry'
if [$array[$test]]
   then
      do something
   else
      something else
fi

注意

我使用bash 4.1.5

I am using bash 4.1.5

推荐答案

在bash 4,你能做的最接近的事是使用关联数组。

With bash 4, the closest thing you can do is use associative arrays.

declare -A map
for name in hello world my name is perseus; do
  map["$name"]=1
done

tgt=henry
if [[ ${map["$tgt"]} ]] ; then
  : found
fi

这篇关于如何检查一个字符串是否在数组中没有遍历元素呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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