gpt4 book ai didi

arrays - 提取 Fortran 字符串数组的子字符串

转载 作者:行者123 更新时间:2023-12-02 08:07:42 27 4
gpt4 key购买 nike

如何提取 Fortran 字符串数组的子字符串?例如

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

用 gfortran 编译会产生错误:

testcharindex.f90:11:10:

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

这里有什么办法可以避免 do 循环吗?如果可以提取字符串数组的索引,我希望应该能够提取字符串数组的动态定义的子字符串(无需遍历数组元素)。我是不是太乐观了?

最佳答案

如果要避免循环并且没有其他(简单)方法,则定义元素子字符串函数并将其应用于字符串数组可能很有用。例如,

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

给出(使用 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

关于arrays - 提取 Fortran 字符串数组的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50069808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com