在字符串数组中查找字符串值

时间:2015-02-24 18:19:27

标签: arrays string fortran fortran90

我在Fortran程序中有一个字符串数组。 单个字符串。我知道数组中的一个值是" foo"。我想知道包含" foo"的数组的索引。有没有办法找到除暴力循环之外的索引?我显然不能使用" minloc"例程,因为我不在这里处理数字。再次,只是为了确保:我不是在字符串中搜索子字符串。我正在搜索字符串数组中的字符串。

2 个答案:

答案 0 :(得分:1)

 implicit none
 integer i
 character*8 a(100)
 do i = 1,100
     a(i)='foo'
 enddo
 a(42)='bar'
 call f(a,len(a(1)),shape(a)*len(a(1)),'bar     ')
 end

 subroutine f(c,n,all,s)
 implicit none
 integer n,all
 character*(*) s
 character*(all) c
 write(*,*)index(c,s)/n+1
 end

 a.out -> 42

请注意,此代码将整个数组视为一个大字符串并搜索子字符串,因此它还会找到与组件字符串边界不对齐的匹配项。

例如。与相邻条目发生错误匹配,例如:

 a(2)='xxbar   '
 a(3)='     yyy'

确保找到{n}的整数倍的index所需的一些额外工作(当然,当你这样做时,一个简单的循环可能看起来更合适)

答案 1 :(得分:0)

好吧,在考虑之后,我想出了这个。如果" foo"众所周知,要么不在阵列中,要么位于一个且只有一个位置:

character(len=3) :: tags(100)
integer :: test(100)
integer :: str_location
! populate "tags" however needed.  Then search for "foo":
test=(/(i,i=1,100)/)
where (tags.ne."foo") test=0
str_location = sum(test)

我猜这实际上比蛮力循环慢,但它使紧凑的代码。我想过填充"测试"使用和使用maxloc,但这并不能解释" foo"不在阵列中。意见?

相关问题