Strings

Working with strings in Fortran has always been a hassle. Especially, variable-length strings were not easy to implement in the past. In modern Fortran, strings with arbitray length are a standard feature and much easier to use.

The programmer can choose between fixed length strings (length is set at declaration), constant strings with variable length (immutable), and variable length strings (number of characters can be changed at run-time). An example uses all types:

! string_test.f90
program main
    use :: iso_varying_string ! Fortran 95 module for old-style variable length strings.
    implicit none
    character(len=5)              :: fix_str = 'fixed'      ! fixed length
    character(len=*), parameter   :: par_str = 'constant'   ! variable length, constant
    type(varying_string)          :: old_str                ! Fortran 95 variable length
    character(len=:), allocatable :: new_str                ! Fortran 2003 variable length

    old_str = 'old-style'
    new_str = 'modern'

    print '(a)', fix_str
    print '(a)', par_str
    print '(a)', char(old_str)
    print '(a)', new_str
end program main

In order to use the Fortran 95 variable length strings, the iso_varying_string module in file iso_vsta.f95 must be compiled and linked:

$ flang -c iso_vsta.f95
$ flang -o string_test string_test.f90 iso_vsta.o
$ ./string_test
fixed
constant
old-style
modern

The recommended way to use variable length strings in modern Fortran is therefor:

character(len=:), allocatable :: str
str = 'Modern variable length string'

String Manipulation

Strings can be concatenated with the // operator:

character(len=:), allocatable :: str
str = 'Modern ' // 'Fortran'

For advanced string manipulation, you can use one of the available Fortran modules: