Extract substring of Fortran string array

后端 未结 3 1174
感动是毒
感动是毒 2020-12-19 18:33

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

program testcharindex
    implicit none
    character(len=10), dimension(5) :: s
             


        
3条回答
  •  既然无缘
    2020-12-19 19:10

    @francescalus has already explained the error, here's my contribution towards the question OP seems really to be tackling, ie how to read the integers from a string array such as

    s = (/ '1_E ', '2_S ', '3_E ', '14_E', '25_S' /)
    

    OP wants to do this without loops, and @roygvib points us towards using an elemental function. Here's my version of such a function to read the integer from a string. This ignores any leading spaces, so should cope with strings such as 12_e. It then stops scanning at the first non-digit character (so reads 12 from a string such as 12_3).

    ELEMENTAL INTEGER FUNCTION read_int(str)
      CHARACTER(*), INTENT(in) :: str
      CHARACTER(:), ALLOCATABLE :: instr
    
      instr = adjustl(str)
      instr = instr(1:VERIFY(instr,'0123456789')-1)
      ! if the string doesn't have a leading digit instr will be empty, return a guard value
      IF(instr=='') instr = '-999'
      READ(instr,*) read_int
    END FUNCTION read_int
    

    I trust that this is clear enough. OP could then write

    n = read_int(s)
    

提交回复
热议问题