Strings

Character handling in Fortran was quite limited in the past, especially, variable-length strings were not easy to implement. 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=8)              :: fix_str              ! Fixed length, variable.
    character(len=:), allocatable :: new_str              ! Fortran 2003 variable length
    type(varying_string)          :: old_str              ! Fortran 95 variable length

    fix_str = 'fixed'
    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:

$ gfortran13 -c iso_vsta.f95
$ gfortran13 -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. For example, the subroutine upper() in the following program converts any given string to upper-case.

! upper.f90
program main
    implicit none
    character(len=:), allocatable :: str

    str = 'Hello, World!'
    call upper(str)

    print '(a)', str
contains
    subroutine upper(str)
        character(len=*), intent(inout) :: str

        character :: a
        integer   :: i

        do i = 1, len(str)
            a = str(i:i)
            if (a >= 'a' .and. a <= 'z') str(i:i) = achar(iachar(a) - 32)
        end do
    end subroutine upper
end program main

The input string Hello, World! will be changed to HELLO, WORLD!:

$ gfortran13 -o upper upper.f90
$ ./upper
HELLO, WORLD!

Fortran Libraries

For advanced string manipulation, several Fortran modules are available: