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

标签 arrays fortran substring

如何提取 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/

相关文章:

fortran - 如何诊断 Fortran 中的总线错误

c# - Xpath标记化函数内部包含函数

java - 如何打印出字符串的所有子串?

fortran - Fortran 中的断言

c++ - 使用 C_LOC() 将指向一维 Fortran 数组的指针传递给 C++ 会导致垃圾值

javascript - 使用javascript根据第二次出现的分隔符拆分字符串

c - 在结构中分配二维数组的值

c++ - 在 C++ 中查找数组的最小值和第二小值

java - 如何使用java onclick shuffle数组

c++ - 动态数组大小并在 getline() 处崩溃;