Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Language Basics

Characters and Strings

Work with text in Fortran: fixed-length character variables, substrings, concatenation, trim, len_trim, index, adjustl, comparisons and allocatable deferred-length strings.

Text in Fortran is stored in character variables. Unlike languages with a built-in string object, a classic Fortran character variable has a fixed length chosen at declaration. This makes text handling a little different from what you may expect, but it is simple once you know the rules, and modern Fortran adds flexible allocatable strings as well.

Declaring character variables

FORTRAN
program strings_intro
  implicit none
  character(len=10) :: name
  character(len=5)  :: code
  character :: initial          ! length 1 by default

  name = "Ada"
  code = "ABCDEFGH"
  initial = "L"

  print *, "[", name, "]"
  print *, "[", code, "]"
  print *, initial
end program strings_intro

What happens to the data:

  • name has length 10 but the value "Ada" is only 3 characters, so the rest is filled with blanks (padding). The stored value is Ada .
  • code has length 5 but the value is 8 characters, so it is truncated to ABCDE.

Both character(len=10) and the old forms character*10 and character(10) mean the same. Strings can use single or double quotes, and a quote inside a string is doubled: 'It''s'.

Length: len and len_trim

len(s) returns the declared length, including padding. len_trim(s) returns the length without trailing blanks:

FORTRAN
character(len=10) :: name = "Ada"
print *, len(name)        ! 10
print *, len_trim(name)   ! 3

Use trim(s) to get the string without trailing blanks, which is what you want before printing it next to other text:

FORTRAN
print *, "Hello, " // trim(name) // "!"     ! Hello, Ada!

Without trim, you would get Hello, Ada ! with seven padding spaces.

Python Stand-in (Python): padding, truncation and trim

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Concatenation and substrings

The // operator joins strings. A substring picks characters by position with string(start:end), counting from 1 and including both ends:

FORTRAN
character(len=20) :: s
s = "Fortran rocks"

print *, s(1:7)       ! Fortran
print *, s(9:13)      ! rocks
print *, s(:3)        ! For   (start defaults to 1)
print *, s(9:)        ! rocks plus padding (end defaults to len(s))

You can assign to a substring too: s(1:1) = "f" changes the first letter without touching the rest. Substring ranges outside 1:len(s) are an error (the compiler with -fcheck=all will tell you).

Python Stand-in (Python): 1-based inclusive substrings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Intrinsic string functions

Function Purpose Example
len(s) declared length len("abc") = 3
len_trim(s) length without trailing blanks
trim(s) remove trailing blanks
adjustl(s) / adjustr(s) shift text left or right, keeping the length
index(s, sub) position of first match, 0 if none index("banana", "an") = 2
index(s, sub, back=.true.) last match = 4
scan(s, set) first char that is in set
verify(s, set) first char that is not in set
repeat(s, n) n copies repeat("ab", 3) = ababab
achar(i) / iachar(c) character from code / code of character achar(65) = A

index is the Fortran search function. It returns 0 when nothing is found, which makes a handy test: if (index(line, "error") > 0) ....

Python Stand-in (Python): index, scan, verify, repeat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Comparing strings

Strings compare with the usual operators, and shorter strings are padded with blanks for the comparison. So "abc" == "abc " is true. Order uses the character codes, so uppercase letters sort before lowercase ones in ASCII. For a guaranteed ASCII order use lge, lgt, lle and llt:

FORTRAN
if (name == "Ada") print *, "Hi Ada"       ! true even though name has trailing blanks
if (llt("apple", "banana")) print *, "apple first"

There is no case-insensitive comparison built in. Convert both sides to one case first, with a short helper you write once (covered in the chapter on procedures).

Allocatable and deferred-length strings

Fortran 2003 introduced strings whose length follows the assigned value:

FORTRAN
character(len=:), allocatable :: line

line = "Hello"
line = line // ", World"       ! line grows automatically
print *, line, len(line)       ! Hello, World 12

Assignment to an allocatable character reallocates it to the length of the right-hand side, no padding. This is the closest thing to the string types of other languages and is what you should use when text size is not known in advance. In older code you will see fixed lengths like character(len=256) as a buffer plus trim.

Converting between text and numbers

Fortran converts with internal I/O: reading from or writing to a string using read and write:

FORTRAN
character(len=20) :: text
integer :: n
real :: x

text = "42"
read (text, *) n            ! n = 42

write (text, "(F6.2)") 3.14159    ! text = "  3.14"

Internal files are the standard way to build file names, parse numbers and format output into strings. They are covered fully in the file I/O chapter; the next lesson introduces read and write.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does character(len=5) :: s; s = "ABCDEFGH" store in s?

    A value longer than the declared length is truncated on the right, leaving ABCDE.
  2. 2. Which expression removes trailing blanks?

    trim removes trailing blanks; adjustl only moves the text to the left inside the same length.
  3. 3. What does index("banana", "an") return?

    The first "an" starts at position 2 (counting from 1).
  4. 4. How do you declare a string that resizes on assignment?

    A deferred-length allocatable character takes the length of the value assigned to it.

Summary

  • A character(len=n) variable has fixed length: short values are blank-padded, long ones are truncated.
  • // concatenates; s(a:b) selects a substring (1-based, inclusive).
  • Use trim, len_trim, adjustl, index, scan, verify, repeat for common tasks.
  • Comparisons pad the shorter string with blanks; lge/lgt compare in ASCII order.
  • character(len=:), allocatable gives resizable strings; internal read/write convert text and numbers.

Next: Reading and Writing Basics