Search code examples
stringappendfortran

Apparently not able to append a string to another


I have a very simple problem, that I am yet to find an answer to.

Is there any way in which I can append a character (in particular, a white space) to a character that has already been initialized in Fortran?

Apparently

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

does not work.


Solution

  • Be aware that all strings are filled with trailing blanks (space characters) after their last non-space character. This is very important!

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

    but

    result = result // ' '
    

    produces a 2001 character string (you are appending to the whole 2000-character result including the trailing blanks), which is then truncated on assignment, so that result ends up being the same.

    You may want

    result = trim(result) // ' '
    

    but it is also useless, because the string is filled with trailing blanks (spaces) anyway.

    It would make sense when you append something non-blank:

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

    It should print abcd.


    If you want to make the variable larger, you have to use:

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

    It works also with space characters:

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

    (In old versions of Intel Fortran one had to enable reallocation on assignment for this behaviour.)