![](/img/trans.png)
[英]Converting a variable length c-string to Fortran string in Visual Studio
[英]Fortran function variable length string return
我正在編寫一個返回字符串的函數
function doc () Result s
character (Len=65) :: s
...
end 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
您可以為此目的使用可分配的字符串:
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
子例程和功能相同。 只有標題不同,但是您可以將結果變量用作任何其他變量。 我最喜歡的示例是將整數轉換為字符串
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
之前使用allocate statement
,但這是多余的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.