0

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.

1
  • [Not a very helpful comment, but:] findloc works on character arrays? [It isn't F90 and isn't widely implemented.] Commented Feb 24, 2015 at 18:44

2 Answers 2

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

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 )

Sign up to request clarification or add additional context in comments.

1 Comment

For the "additional work", you presumably mean to handle something like call f(['fob','arb','bar'], 3, 9, 'bar')? [There's an argument missing in your call.]
0

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?

1 Comment

If you want "compact" in the absence of findloc then minval(pack([(i,i=1,100)],tags.eq.'foo')). But that's not really a good way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.