Vin*_* W. 3 string fortran list
经过大量挖掘,我已经为 Fortran 中的可变长度字符串列表制定了一个家庭酿造方案。它实际上是一个自定义类型的数组,只有一个成员属性,它是一个可变长度的字符串。语法有点麻烦,我想知道是否有我找不到的更好的方法。
这是我所拥有的:
! scratch.f90
module string_list
type t_string
character(len=:), allocatable :: s
end type
end module
program main
use string_list
implicit none
integer i
type(t_string), allocatable :: list(:)
allocate(list(2))
list(1)%s = "hi my name is"
list(2)%s = "slim shady"
do i=1,2
print *, len(list(i)%s)
end do
end program
Run Code Online (Sandbox Code Playgroud)
编译 gfortran scratch.f90 -o scratch
然后:
> ./scratch
13
10
Run Code Online (Sandbox Code Playgroud)
就像评论所暗示的那样,您的方法可能是一个好的开始。为了使语法更简单,您可以制作一些类型绑定的运算符和过程,例如:
module string_list
implicit none
type str
character(:), allocatable :: s
contains
procedure :: assa, get, length
generic :: assignment(=) => assa
generic :: operator(-) => get
generic :: l => length
end type
contains
subroutine assa(st,str1)
class(str), intent(out) :: st
character(*), intent(in) :: str1
st%s = str1
end
function get(st1) result(str1)
class(str), intent(in) :: st1
character(:), allocatable :: str1
str1 = st1%s
end
function length(st1) result(nn)
class(str), intent(in) :: st1
integer :: nn
nn = len(st1%s)
end
end
program test
use string_list, only: str
implicit none
type(str), dimension(:), allocatable :: stra
allocate(stra(2))
stra(1) = "hello "
stra(2) = "fortran"
print*, -stra(1)
print*, -stra(1)//-stra(2)
print*, stra(1)%l(), stra(2)%l()
print*, len(-stra(1)), len(-stra(2))
end
Run Code Online (Sandbox Code Playgroud)
结果是
hello
hello fortran
6 7
6 7
Run Code Online (Sandbox Code Playgroud)
这可能不是最聪明的设计,我只是出于兴趣尝试了一些东西。这里我重载了-幺正运算符来提取实际的字符串,并=进行赋值,以避免%s语法,并添加了一个更方便的长度函数。
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |