How does one extract a substring of a Fortran string array? For example
program testcharindex
implicit none
character(len=10), dimension(5) :: s
In case loop is to be avoided and there is no other (simple) methods, it might be useful to define an elemental substring function and apply it to an array of strings. For example,
module str_mod
implicit none
contains
elemental function substr( s, a, b ) result( res )
character(*), intent(in) :: s
integer, intent(in) :: a, b
character(len(s)) :: res
res = s( a : b )
endfunction
endmodule
program main
use str_mod
implicit none
character(10) :: s( 5 )
integer, allocatable :: ind(:)
character(len(s)), allocatable :: comp(:)
s = [ '1_E ', '2_S ', '3_E ', '14_E', '25_S' ]
! s = [ character(len(s)) :: '1_E', '2_S', '3_E', '14_E', '25_S' ]
print *, "test(scalar) : ", substr( s(1), 1, 2 )
print *, "test(array ) : ", substr( s, 1, 2 )
ind = index( s, '_' )
comp = substr( s, 1, ind-1 )
print *
print *, "string (all) : ", s
print *, "string before _ : ", comp
print *, "string after _ : ", substr( s, ind+1, len(s) )
endprogram
which gives (with gfortran-7.3)
test(scalar) : 1_
test(array ) : 1_ 2_ 3_ 14 25
string (all) : 1_E 2_S 3_E 14_E 25_S
string before _ : 1 2 3 14 25
string after _ : E S E E S