1

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.

1 Answer 1

1

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.

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

3 Comments

Thanks,Is there some standard reference for learning fortran, as I couldn't find the proper definition of intrinsic function used above.
You can read the language standards (links found here), but your compiler's documentation is likely to provide such descriptions also.
@SameeranJoshi If you want a book I would recommend oxfordscholarship.com/view/10.1093/oso/9780198811893.001.0001/…

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.