Character Strings
For variable-length string collections use a derived type wrapper (type :: string; character(:), allocatable :: s; end type) or stdlib_string_type.
12.1 Declarations
character(len=20) :: fixed = "Fortran" ! padded with blanks to length 20
character(len=:), allocatable :: dyn ! deferred length (grows automatically)
character(len=*), parameter :: msg = "constant"
character :: c ! length 1
dyn = "hello"
dyn = dyn // ", world" ! automatic reallocation12.2 Operations & intrinsics
s = " Hello, Fortran "
len(s), len_trim(s) ! total length, length without trailing blanks
trim(s), adjustl(s), adjustr(s) ! remove trailing blanks, shift left/right
s(3:7) ! substring "Hello"
s(3:3) ! single character
index(s, "Fortran") ! position of substring (0 if absent)
index(s, "o", back=.true.) ! last occurrence
scan(s, "aeiou"), verify(s, " ") ! first char in set / first not in set
repeat("ab", 3) ! "ababab"
achar(65), iachar('A'), char(10), ichar('a')
new_line('a') ! newline character
lge(a, b), lgt, lle, llt ! ASCII-ordered comparisons
s1 == s2 ! comparison pads shorter with blanks12.3 Upper/lower case (no intrinsic before F2023 — write your own)
pure function to_upper(s) result(r)
character(len=*), intent(in) :: s
character(len=len(s)) :: r
integer :: i, c
r = s
do i = 1, len(s)
c = iachar(s(i:i))
if (c >= iachar('a') .and. c <= iachar('z')) r(i:i) = achar(c - 32)
end do
end function to_upper12.4 Internal I/O — converting numbers ↔ strings
character(len=32) :: buf
integer :: n
real :: x
write(buf, '(i0)') 42 ! integer → string "42"
write(buf, '(f0.3)') 3.14159 ! "3.142"
read("123", *) n ! string → integer
read(buf, *) x
! Fortran 2023 / stdlib alternatives: to_string(), split(), etc. (see stdlib_strings)12.5 Arrays of strings
For variable-length string collections use a derived type wrapper (type :: string; character(:), allocatable :: s; end type) or stdlib_string_type.
character(len=10) :: words(3) = [character(len=10) :: "alpha", "beta", "gamma"]
do i = 1, size(words)
print *, trim(words(i))
end do