LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1476|回复: 7

怎样从数组中统计字符串的个数?

[复制链接]
发表于 2006-3-20 20:28:49 | 显示全部楼层 |阅读模式
数组a中
a[1]="aaaa"
a[2]="abcde"
a[3]="aaaa"
a[4]="sdfssdf"

想统计 "aaaa"的个数

请问应该怎么写呀?
发表于 2006-3-21 00:01:00 | 显示全部楼层
  1. j=0; for((i=1;i<=${#a[@]};i++)); do if [[ ${a[$i]} = "aaaa" ]]; then j=$(($j+1));fi;done;echo $j
复制代码
Will this help?
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-3-21 09:33:05 | 显示全部楼层
谢谢,老大
回复 支持 反对

使用道具 举报

发表于 2006-3-21 13:03:49 | 显示全部楼层
Post by yongjian
  1. j=0; for((i=1;i<=${#a[@]};i++));if [[ ${a[$i]} = "aaaa" ]]; then j=$(($j+1));done;echo $j
复制代码
Will this help?
这条语句我在我机器上试了一下,报了个错误:
-bash: syntax error near unexpected token `if'
不知道为什么?另外,${#a[@]}用的可真妙,可我不太懂它的意思,斑竹能不能给我说一下在这里#和@的意思啊?
回复 支持 反对

使用道具 举报

发表于 2006-3-29 17:01:49 | 显示全部楼层
${#a[@]}这个是数组的最后一个索引ID,记得perl里应该用$#a来表示,不知道对不对?
回复 支持 反对

使用道具 举报

发表于 2006-3-30 02:08:25 | 显示全部楼层
Ya, I missed a fi there, just added. And ${#a[@]} is the notation to count the number of elements in an array. ${#a
  • } is the same. It is not the last element's index ID.

    EDIT: In Perl, $#a is the same of the last index.
  • 回复 支持 反对

    使用道具 举报

    发表于 2006-3-30 15:48:06 | 显示全部楼层
    Post by yongjian
    Ya, I missed a fi there, just added. And ${#a[@]} is the notation to count the number of elements in an array. ${#a
  • } is the same. It is not the last element's index ID. Same thing, in perl $#a counts the number in @a but not the index of the last element.


  • To yongjian,

    In perl, $#a is the last index of an array.
    回复 支持 反对

    使用道具 举报

    发表于 2006-3-30 23:50:42 | 显示全部楼层
    you'r right Johnny... Somehow I remember perl and shell calca the sam way.. but that is apparently wrong. Thread updated. Thanks to pint out!

    EDIT: @a without the array context will show the number of element. I mismatched them.
    回复 支持 反对

    使用道具 举报

    您需要登录后才可以回帖 登录 | 注册

    本版积分规则

    快速回复 返回顶部 返回列表