Looping over characters in Fortran

心不动则不痛 提交于 2020-06-23 08:11:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!