如何将字符数组传递到字符串中

4

我想知道如何将字符数组转换为多个字符字符串。实际上,我有一个包含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...

我希望能够在一个 for 循环中递归地将 FILE_SIM_all 的“sim”行(sim=1,17)转换为字符字符串。就像这样:
do sim=1,17
    FILE_SIM(1:29) = FILE_SIM_all(1:29,sim)
enddo

但是在编译我的程序时,我遇到了以下错误:

error #6366: 数组表达式的形状不一致。 [FILE_SIM]

我做错了什么?谢谢!

1个回答

5

从问题的简单变体开始,要从长度为一的字符数组中创建一个与指定长度相同的字符标量,可以使用赋值语句。

! 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

使用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

请注意,在Fortran中,标量与数组是非常不同的。如果您将一个标量赋值给一个数组,您将该标量的值分配给数组中的每个元素,就好像您编写了arrary(1) = scalar ; array(2) = scalar ; ...
还要注意,内置字符赋值如果右侧的长度与左侧的长度不匹配,则会截断(或填充)。
因此,在您的代码中:
FILE_SIM_all(1:29,1) = "/Users/toto/Documents/toto.nc"

这个语句给一个数组部分赋值标量,除非你想要29个单斜杠字符,否则没有任何用处!

在您的示例中出现错误消息是因为您试图将大小为29的数组部分赋值给标量(长度为29的字符对象)。一般来说,您不能将数组(等级为1或更高)赋值给标量(等级为0)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接