Fortran函数变长字符串返回

时间:2022-01-15 19:39:31

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 can allocate 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

2 个解决方案

#1


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

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

结果变量在赋值时分配。您可以在赋值之前使用allocate语句,但这是多余的。

#2


You can use allocatable strings for this purpose:

您可以为此目的使用可分配字符串:

module str_mod
  implicit none

contains 

function str2str(str) result(s)
  implicit none
  character(len=*),intent(in)   :: str
  character(len=:),allocatable  :: s

  allocate( character(len=2*len(str)) :: s )
  s = str // str
end function

end module

program test
  use str_mod
  print *,str2str('test')
end program

#1


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

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

结果变量在赋值时分配。您可以在赋值之前使用allocate语句,但这是多余的。

#2


You can use allocatable strings for this purpose:

您可以为此目的使用可分配字符串:

module str_mod
  implicit none

contains 

function str2str(str) result(s)
  implicit none
  character(len=*),intent(in)   :: str
  character(len=:),allocatable  :: s

  allocate( character(len=2*len(str)) :: s )
  s = str // str
end function

end module

program test
  use str_mod
  print *,str2str('test')
end program