Fortran函数可变长度字符串返回

Fortran函数可变长度字符串返回

本文介绍了Fortran函数可变长度字符串返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个返回字符串的函数

I am writing a function to return a string

function doc () Result s
character (Len=65) :: s
...
end function

是否可以使用可变长度的字符串,我可以分配要返回的字符串的长度.我知道我可以使用子例程来执行此操作,但是不能使用函数.

Is it possible to have a variable length string, where I canallocate the length of the string being returned. I know I can do it using a subroutine, but not for a function.

Function discl (nm) Result (s)

Character (Len=:), Allocatable :: s
Character (Len=*), Intent (In) :: nm

Integer :: n
Character (Len=65) :: stamp
stamp = "Thu May  7 15:13:48 BST 2015"

n = Len_trim (stamp)
Allocate (Character (n) :: s)
s = Trim (fstamp)

End Subroutine discl

推荐答案

子例程和函数相同.只有标题不同,但是您可以将结果变量用作任何其他变量.我最喜欢的示例是将整数转换为字符串

It is the same for a subroutine and for a function. Only the header differs, but you can use the result variable as any other variable. My favourite example is the conversion of an integer to a string

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

结果变量在分配时分配.您可以在分配前使用allocate statement,但这很多余.

the result variable is allocated on assignment. You could use an allocate statement before the assignment, but that is redundant.

这篇关于Fortran函数可变长度字符串返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 05:02