问题
I would like to know if it is possible to loop over strings in Fortran. For example I would like to know if the following code:
DO p=a,b,c,t,r
...
END DO
would replace a b c t and r whenever a p is writen.
回答1:
A loop index is always a scalar integer. Fortunately it's a simple enough matter to use an array of the desired "iterated" objects:
character, parameter :: ps(*) = ['a', 'b', 'c', 't', 'r']
integer i
character p
do i=1, SIZE(ps)
p = ps(i)
...
end do
This idiom holds for more than just characters.
回答2:
Or, if by string OP means a character variable of length n
, one might have something like
character(len=n) :: string
...
string = 'abcdef'
...
do i = 1,n
write(*,*) string(i:i)
end do
noting that for taking substrings of any length (including 1
) both start and end indices have to be supplied
来源:https://stackoverflow.com/questions/47581965/looping-over-characters-in-fortran