Silverfrost Forums

Welcome to our forums

INTRINSIC FUNCTION INDEX not scanning from end of string

26 Feb 2015 11:29 #15765

The intrinsic function INDEX scans a string for the position of the first occurrence of a substring.

Here I am searching for the character '9' in the string '1234567890'

Running the code below shows this works fine when the option back is logical .false. - the return value is 9, if .true. i.e. scanning from the end of the sting, when I run this code the return value is 9, which is wrong - it should be 2. Or am I doing something silly here - it's very late here in the UK - well past my bedtime!

Thanks

Ken

  program test
  implicit none
  character (len=10) w  
  integer i
  logical back
  
  w = '1234567890'
  write(6,'(a)')w
  
  back = .false.
  i = INDEX(w,'9',back )
  write(6,*) i
  
  back = .true.
  i = INDEX(w,'9',back )
  write(6,*) i

  i = INDEX(w,'9')
  write(6,*) i
  
  end program test
27 Feb 2015 12:00 #15766

Substring indices are always counted from the left to right, starting with 1. One motivation is that after the index value i has been obtained, one should be able to assume that w(i:i) will equal the character searched for.

I do not know if there are semitic variants of Fortran where things are done otherwise. See the compiler documentation for the intrinsic function INDEX.

To clarify the issue, try running your program with **w **= '1239567890' instead.

27 Feb 2015 4:09 #15768

index(...) finds either the first or the last position of a substring within a string, always counting from left:

      winapp
      program test 
      implicit none
      include <windows.ins> 

      integer*4     i,j
      character*20  string

      string = 'abcd47abcd47abcd4711'

      i = index(string,'47')
      j = index(string,'47',.true.)
      print*,i,j   !! 5 and 17

      i = index(string,'4711')
      j = index(string,'4711',.true.)
      print*,i,j   !! both 17
      end

In the first part index searches for '47' which appears three times - at position 5, 11 and 17. In the second part '4711' is searched which appears only once.

27 Feb 2015 6:15 #15770

Thanks guys, I missed the point that the position is always counted from the left. Obvious really! Thanks Ken

Please login to reply.