String Manipulation

Character handling in Fortran can sometimes be quite limited, especially, variable-length strings were not easy to implement in the past. Since Fortran 2003, strings with arbitray length have become a standard feature. Some compilers provide basic Unicode support.

We 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 declares all types:

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

    new_str = 'modern'
    old_str = 'f95'

    print '(a)', con_str
    print '(a)', fix_str
    print '(a)', new_str
    print '(a)', char(old_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:

$ gfortran10 -c iso_vsta.f95
$ gfortran10 -o strings strings.f90 iso_vsta.o
$ ./strings
constant
fixed
modern
f95

Strings can be concatenated with the // operator:

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'

Libraries

For advanced string manipulation, several Fortran modules are available: