【问题标题】:Apparently not able to append a string to another显然无法将字符串附加到另一个
【发布时间】:2013-04-26 22:36:59
【问题描述】:

我有一个非常简单的问题,我还没有找到答案。

有什么方法可以将字符(特别是空格)附加到已经在 Fortran 中初始化的字符上?

显然

CHARACTER(2000) :: result
result = ''
result = result // ' '

不工作。

【问题讨论】:

    标签: string append fortran


    【解决方案1】:

    请注意,所有字符串在最后一个非空格字符之后都用尾随空格(空格字符)填充。这很重要!

    'a' // ' ' really produces  'a '
    

    但是

    result = result // ' '
    

    生成一个 2001 字符的字符串(您将附加到整个 2000 个字符的 result,包括尾随空格),然后在赋值时将其截断,因此 result 最终是相同的。

    你可能想要

    result = trim(result) // ' '
    

    但它也没有用,因为无论如何字符串都填充了尾随空格(空格)。

    当你附加一些非空白的东西时会有意义:

      character(4) :: str
    
      str = "a"
      str = trim(str) // "bcd"
      print *, str
    end
    

    它应该打印abcd


    如果你想让变量变大,你必须使用:

    character(:), allocatable:: result
    result = 'a'  !now contains 'a' and has length 1
    result = result // 'b' !now contains 'ab' and has length 2
    

    它也适用于空格字符:

    character(:), allocatable:: result
    result = ' '  !now contains ' ' and has length 1
    result = result // ' ' !now contains '  ' and has length 2
    

    (在旧版本的 Intel Fortran 中,必须为这种行为启用重新分配分配。)

    【讨论】:

    • 您好,谢谢您的回答。似乎我可能有其他一些与编译器相关的问题,因为我之前找到了一个类似的例子,但就像以前一样,当我尝试初始化任何变量而不给它一个静态大小时,这是输出:Compiling the source code.... $gfortran demo.f95 -o demo 2>&1 demo.f95:5.14: character(:),allocatable:: result 1 错误:(1) demo.f95:48.10 的 CHARACTER 声明中的语法错误:result = '' 1 错误: (1) 处的符号“结果”没有隐式类型
    • 获取最新版本的编译器。现在唯一支持的是 4.6.4、4.7.3 和 4.8.0。对于可分配字符,我推荐最新的 4.8.0。在 4.6 中,它们根本不工作 AFAIK。
    • 但是即使是普通字符你也可以做很多有用的程序,只要确保它们有固定长度并用空格填充,你可以使用trim函数。
    • 非常感谢您的建议。我明天去拿它。最好的问候!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 2011-05-25
    • 2014-10-05
    • 1970-01-01
    相关资源
    最近更新 更多