Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract substring of Fortran string array

How does one extract a substring of a Fortran string array? For example

program testcharindex
    implicit none
    character(len=10), dimension(5) :: s
    character(len=10), allocatable :: comp(:)
    integer, allocatable  :: i(:), n(:)
    s = (/ '1_E ', '2_S ', '3_E ', '14_E', '25_S' /)
    i = index(s,'_')
    print *,' i = ', i
    n = s(1:i-1) ! or n = s(:i-1)
    comp = s(i+1:)
    print *,' n = ', n
    print *,' comp = ', comp
end program

Compiling with gfortran yields the error:

testcharindex.f90:11:10:

n = s(1:i-1) 1 Error: Array index at (1) must be scalar

Is there any way of avoiding a do loop here? If one can extract an index of a string array, I would expect that one should be able to extract a dynamically-defined substring of a string array (without looping over the array elements). Am I too optimistic?

like image 810
gammarayon Avatar asked Apr 22 '26 15:04

gammarayon


1 Answers

You have a couple of problems here. One of which is easily addressed (and has been in other questions: you can find these for more detail).

The line1

n = s(1:i-1)

about which the compiler is complaining is an attempt to reference a section of the array s, not an array of substrings of elements of array s. To access the substrings of the array you will need

n = s(:)(1:i-1)

However, this is related to your second problem. As the compiler complains for accessing the array section, the i must be a scalar. This is also true for the case of accessing substrings of an array. The above line will still not work.

Essentially, if you wish to access substrings of an array, each substring has to have exactly the same structure. That is, in s(:)(i:j) both i and j must be scalar integer expressions. This is motived by the desire to have every element of the returned array being the same length.

You will, then, need to use a loop.


1 As High Performance Mark once commented, there's also a problem with the assignment itself. I considered simply the expression on the right-hand side. Even corrected for a valid array substring, the expression is still a character array, which cannot be assigned to the integer scalar n as desired.

If you want the literal answer about selecting substrings then read as above. If you simply care about "converting part of a character array to an integer array" then another answer covers things well.

like image 166
francescalus Avatar answered Apr 25 '26 05:04

francescalus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!