Fortran String Functions
Fortran's intrinsic string functions are fewer than Python's, but they cover searching, trimming, aligning and converting text. This lesson tours them and shows how to build the missing pieces (upper case, splitting, number conversion) yourself.
Searching: index, scan, verify
program searching
implicit none
character(len=*), parameter :: path = 'data/run_042/output.csv'
print '(a, i0)', 'first "/": ', index(path, '/')
print '(a, i0)', 'last "/": ', index(path, '/', back=.true.)
print '(a, i0)', '"run" starts at: ', index(path, 'run')
print '(a, i0)', '"xyz" found at: ', index(path, 'xyz') ! 0 = not found
print '(a, i0)', 'first digit: ', scan(path, '0123456789')
print '(a, i0)', 'first non-letter:', verify(path, 'abcdefghijklmnopqrstuvwxyz')
print '(a)', 'file name: ' // path(index(path, '/', back=.true.) + 1:)
end program searchingfirst "/": 5
last "/": 13
"run" starts at: 6
"xyz" found at: 0
first digit: 10
first non-letter:5
file name: output.csv
| Function | Returns |
|---|---|
index(s, sub [, back]) |
position of the first (or last) occurrence of sub, or 0 |
scan(s, set [, back]) |
position of the first character of s that is in set |
verify(s, set [, back]) |
position of the first character of s that is not in set (0 if all are) |
Alignment and repetition
program align
implicit none
character(len=12) :: word
word = ' centred'
print '(3a)', '[', word, ']'
print '(3a)', '[', adjustl(word), ']' ! move leading blanks to the end
print '(3a)', '[', adjustr(word), ']' ! move trailing blanks to the front
print '(3a)', '[', trim(adjustl(word)), ']'
print '(a)', repeat('=-', 10)
end program align[ centred ]
[centred ]
[ centred]
[centred]
=-=-=-=-=-=-=-=-=-=-
trim(adjustl(s)) removes blanks on both sides, the equivalent of Python's strip().
Upper and lower case
There is no built-in upper function, but the ASCII codes make it a short loop. We write it as an internal function (functions are explained in detail soon):
program case_convert
implicit none
print '(a)', to_upper('Hello, Fortran 2018!')
contains
function to_upper(s) result(u)
character(len=*), intent(in) :: s
character(len=len(s)) :: u
integer :: i, code
u = s
do i = 1, len(s)
code = iachar(s(i:i))
if (code >= iachar('a') .and. code <= iachar('z')) u(i:i) = achar(code - 32)
end do
end function to_upper
end program case_convertHELLO, FORTRAN 2018!
Converting numbers and strings: internal I/O
To turn a number into text, write it into a character variable instead of a file; to parse text, read from a character variable (it must be a variable, not a literal). This is called internal I/O:
program conversions
implicit none
character(len=20) :: buffer
integer :: n, ios
real :: x
! number -> string
write(buffer, '(i0)') 1234
print '(3a)', '[', trim(buffer), ']'
write(buffer, '(f0.3)') 2.0 / 3.0
print '(3a)', '[', trim(buffer), ']'
! string -> number
buffer = ' 42 '
read(buffer, *) n
buffer = '6.25e-1'
read(buffer, *) x
print '(i0, 1x, f6.4)', n, x
! detect bad input with iostat
buffer = 'forty-two'
read(buffer, *, iostat=ios) n
print '(a, l1)', 'conversion failed: ', ios /= 0
end program conversions[1234]
[.667]
42 0.6250
conversion failed: T
Notice [.667]: with f0.d, gfortran omits the optional leading zero of numbers below 1 (the standard leaves it up to the compiler). Use a fixed width such as f6.3 when you need the zero.
The Internal & scratch-file I/O lesson goes further with this technique.
Splitting a string into words
A small loop with index splits a sentence on blanks:
program split_words
implicit none
character(len=:), allocatable :: rest
integer :: pos, count
rest = 'the quick brown fox jumps'
count = 0
do while (len_trim(rest) > 0)
rest = adjustl(rest) ! drop leading blanks
pos = index(rest, ' ')
if (pos == 0) pos = len(rest) + 1 ! last word
count = count + 1
print '(i0, a, a)', count, ': ', rest(1:pos - 1)
rest = rest(pos:)
end do
end program split_words1: the
2: quick
3: brown
4: fox
5: jumps
Character codes
| Function | Purpose |
|---|---|
iachar(c) / achar(n) |
ASCII code ↔ character |
ichar(c) / char(n) |
the same, for the processor's character set |
new_line('a') |
the newline character |
lge, lgt, lle, llt |
comparisons in ASCII order |
program codes
implicit none
character(len=*), parameter :: word = 'Fortran'
integer :: i, checksum
checksum = 0
do i = 1, len(word)
checksum = checksum + iachar(word(i:i))
end do
print '(a, i0)', 'ASCII sum of "Fortran": ', checksum
print '(a)', 'Line one' // new_line('a') // 'Line two'
end program codesASCII sum of "Fortran": 732
Line one
Line two
Test yourself
What does index('banana', 'na') return?
- 2
- 3
- 5
- 0
How do you convert the integer n into a string s with no padding?
s = ns = str(n)write(s, '(i0)') nread(s, *) n
Which expression removes blanks from both ends of s?
trim(s)adjustl(s)trim(adjustl(s))adjustr(s)