Reputation: 69
I have compiled code with gfortran and AOCC flang compiler, but it fails for both, is there anything wrong I am doing?
program find_sub_indx
implicit none
!decl
character(len =30) :: main_string, sub_string
integer :: index_1 , index_2
logical :: back
!defn
main_string = "this is the main string"
sub_string = "a"
back = .false.
index_1 = INDEX(main_string, sub_string, back) !why does this not work
index_2 = INDEX("this is the main string","a", .false.) !this works why?
print *, "index_1 is " , index_1, index_2
end program find_sub_indx
Result expected:
index_1 is 14 14
Actual result:
index_1 is 0 14
Is there some standard reference for learning fortran, as I couldn't find the proper definition of intrinsic function used above.
Upvotes: 1
Views: 165
Reputation: 32451
In the first attempt to use index
INDEX(main_string, sub_string, back)
the variables main_string
and sub_string
are both of length 30. After the assignment
sub_string = "a"
the variable sub_string
has value starting with a
but has 29 trailing spaces after that.
So, the function is evaluated like
INDEX(main_string, 'a ', back)
That substring is, of course, not found in main_string
and the result is correctly 0
.
You can instead use
INDEX(main_string, TRIM(sub_string), back) !or
INDEX(main_string, sub_string(1:1), back)
or declare sub_string
to be of length 1
.
The literal constant "a"
in the second attempt has length 1 and does not have these trailing spaces.
Upvotes: 1