Character-returning function of unknown length

寵の児 提交于 2019-12-21 21:03:36

问题


How to use character function of where the result is of unknown length initially?

The trim() function, I understand, shows that it is possible not to specify the length of returning string.

For example:

write (*,*) trim(str)

will return only part of the string without trailing spaces.

This function does not have any idea about the length of returning string before the call.

Or trim() function has limitations?

On more variant is to find original code of trim() function.

I have found (Returning character string of unknown length in fortran) but it is not the answer to my question.

To be sure, I want to write function, that returns string by integer number.

Something like this:

function strByInt(myInt)
...
write (strByInt,fmt) myInt; return
end function strByInt

somewhere else:

write (*,*) strByInt(50) ! will write '50'

回答1:


That question you referenced partially answers it. It mentions the allocatable characters with deferred length. See below my implementation I use regularly:

  function strByInt(i) result(res)
    character(:),allocatable :: res
    integer,intent(in) :: i
    character(range(i)+2) :: tmp
    write(tmp,'(i0)') i
    res = trim(tmp)
  end function

The result variable is allocated on assignment on the last line to fit the answer.

The trim function is a different beast, as an intrinsic function it doesn't have to be programmed in Fortran and can obey different rules. It just returns what it needs to return. But it could be as well implemented as above quite easily.




回答2:


Fortran2003 has variable character length feature. Here is a sample code. This program outputs "Beep!Beep!" string.

module m_test
  implicit none
contains
  function say2(text)
    character(len = *), intent(in) :: text
    character(len = :), allocatable :: say2
    say2 = trim(text) // trim(text)
    return
  end function say2
end module m_test

program String
  use m_test
  implicit none
  print *, say2('Beep!   ')
  stop
end program String

Following line declares variable length character variable.

character(len = :), allocatable :: say2

You might need "/standard-semantics" or "Enable F2003 semantics" in Intel Fortran.



来源:https://stackoverflow.com/questions/22460220/character-returning-function-of-unknown-length

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