如何将字符数组传递给字符串

T.D*_*Des 4 arrays string fortran character fortran90

我想知道如何从一个字符数组到几个字符串。事实上,我有一个包含 17 个文件路径的字符数组。让我们说:

character, dimension(29,17) :: FILE_SIM_all
character, length(29) :: FILE_SIM

! Declarations end

FILE_SIM_all(1:29,1) = "/Users/toto/Documents/toto.nc"
FILE_SIM_all(1:29,2) = etc...
Run Code Online (Sandbox Code Playgroud)

我想递归地(在 sim=1,17 的 for 循环中)将 FILE_SIM_all 的“sim”行转换为字符串。让我们说类似的话

do sim=1,17
    FILE_SIM(1:29) = FILE_SIM_all(1:29,sim)
enddo
Run Code Online (Sandbox Code Playgroud)

但是在编译我的程序时出现以下错误:

错误 #6366:数组表达式的形状不符合。[FILE_SIM]

我究竟做错了什么?谢谢 !

Ian*_*anH 5

从该问题的一个更简单的变体开始,要从与特定长度具有相同大小的长度为 1 的第 1 个字符数组创建特定长度的字符标量,您可以使用赋值语句。

! Declare vector to be an rank one array of size ten of 
! length one characters.
CHARACTER(1) :: vector(10)
! Declare scalar to be a character scalar of length ten, 
! so LEN(scalar) == SIZE(vector)
CHARACTER(10) :: scalar
INTEGER :: i     ! Loop index.

! Define `vector`.  Note that the right hand side of the 
! assignment is a rank one array of ten length one characters, 
! consistent with the definition of vector.
vector = (/ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' /)

! Loop over the elements of `vector` and the characters of 
! `scalar` and transfer the individual characters.
DO i = 1, LEN(scalar)  ! or SIZE(vector)
  scalar(i:i) = vector(i)
END DO
Run Code Online (Sandbox Code Playgroud)

(FORALL 语句可能更简洁一些,尤其是在 F2008 中。)

您的问题只是在上面增加了另一个等级。

! Declare `matrix` to be an rank two array of shape (10,2) of 
! length one characters.
CHARACTER(1) :: `matrix`(10,2)
! Declare `list` to be a rank one array of size 2 and 
! length ten, so LEN(list) == SIZE(matrix,1) and 
! SIZE(list) == SIZE(matrix,2)
CHARACTER(10) :: list(2)
INTEGER :: i     ! Inner Loop index.
INTEGER :: j     ! Outer loop index.

! Define `matrix`.  Note that the right hand side of each 
! assignment is a rank one array of ten length one characters, 
! consistent with the definition of a column of matrix.
matrix(:,1) = (/ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' /)
matrix(:,2) = (/ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' /)

! Loop over the columns of matrix and the elements of list.
DO j = 1, SIZE(list)   ! or SIZE(matrix,1)
  ! Loop over the rows of `matrix` and the characters of 
  ! an element of `list` and transfer the individual characters.
  DO i = 1, LEN(list)   ! or SIZE(matrix,2)
    list(j)(i:i) = matrix(i,j)
  END DO
END DO
Run Code Online (Sandbox Code Playgroud)

请注意,Fortran 中的标量与数组非常不同。如果将标量分配给数组,则将该标量的值分配给数组中的每个元素,就好像您已编写arrary(1) = scalar ; array(2) = scalar ; ...

另请注意,如果右侧的长度与左侧的长度不匹配,则内部字符分配会截断(或填充)。

因此在您的代码中:

FILE_SIM_all(1:29,1) = "/Users/toto/Documents/toto.nc"
Run Code Online (Sandbox Code Playgroud)

将标量分配给数组部分,不会做任何有用的事情,除非您想要 29 个单斜杠字符!

您的示例中出现错误消息是因为您试图将大小为 29 的数组部分分配给标量(恰好是长度为 29 的字符对象)。通常,您不能将数组(等级为 1 或更大)分配给标量(等级为零)。