Zeu*_*eus 1 string fortran function
我正在写一个函数来返回一个字符串
function doc () Result s
character (Len=65) :: s
...
end function
Run Code Online (Sandbox Code Playgroud)
是否可以使用可变长度字符串,我可以在其中分配返回的字符串的长度.我知道我可以使用子程序来完成它,但不能用于函数.
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
Run Code Online (Sandbox Code Playgroud)
您可以为此目的使用可分配的字符串:
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
Run Code Online (Sandbox Code Playgroud)
子程序和函数都是一样的.只有标题不同,但您可以将结果变量用作任何其他变量.我最喜欢的例子是将整数转换为字符串
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
Run Code Online (Sandbox Code Playgroud)
结果变量在赋值时分配.您可以allocate statement在分配之前使用,但这是多余的.
| 归档时间: |
|
| 查看次数: |
1914 次 |
| 最近记录: |