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. Some Fortran compilers even provide basic Unicode support.

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:

! strings.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 strings strings.f90 iso_vsta.o
$ ./strings

The recommended way to implement 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'

Use the index of the string to access or change single characters. The first character can be changed to lower-case with:

str(1:1) = 'm'

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