bob.sacamento
bob.sacamento

Reputation: 6661

Find a string value in an array of strings

I have an array of strings in a Fortran program. Not a single character string. I know that one of the values in the array is "foo". I want to know the index of the array that contains "foo". Is there a way to find the index other than a brute force loop? I obviously can't use the "minloc" routine since I'm not dealing with numerics here. Again, just to make sure: I am not searching for a substring in a string. I am searching for a string in an array of strings.

Upvotes: 0

Views: 1433

Answers (2)

bob.sacamento
bob.sacamento

Reputation: 6661

Well, after thinking about it, I came up with this. It works if "foo" is known to be either absent from the array, or located in one and only one place:

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)

I am guessing this is actually slower than the brute force loop, but it makes for compact code. I thought about filling "test" with ones and using maxloc, but that doesn't account for the possibility of "foo" be absent from the array. Opinions?

Upvotes: 0

agentp
agentp

Reputation: 6999

 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

note this code is treating the entire array as one big string and searching for substrings so it will also find matches that are not aligned with the component string boundaries.

eg. a false match occurs with adjacent entries such as:

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

Some additional work required to ensure you find an index that is an integer multiple of n ( of course by the time you do that a simple loop might look preferable )

Upvotes: 1

Related Questions