Fortran Data Types Accessing character substrings


For the character entity

character(len=5), parameter :: greeting = "Hello"

a substring may be referenced with the syntax

greeting(2:4)  ! "ell"

To access a single letter it isn't sufficient to write

greeting(1)    ! This isn't the letter "H"


greeting(1:1)  ! This is "H"

For a character array

character(len=5), parameter :: greeting(2) = ["Hello", "Yo!  "]

we have substring access like

greeting(1)(2:4)  ! "ell"

but we cannot reference the non-contiguous characters

greeting(:)(2:4)  ! The parent string here is an array

We can even access substrings of literal constants


A portion of a character variable may also be defined by using a substring as a variable. For example

integer :: i=1
character :: filename = 'file000.txt'

filename(9:11) = 'dat'
write(filename(5:7), '(I3.3)') i