Extract substring of Fortran string array

后端 未结 3 1173
感动是毒
感动是毒 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 18:55

    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.

提交回复
热议问题