String tools
| Trim and len_trim | |
| Adjustl and adjustr | |
| Index and scan | |
| Verify sets |
Trim and len_trim
Fortran pads short strings with blanks, which breaks comparisons and messages. Len reports the declared length while len_trim reports the length without trailing blanks. Trim removes the padding when building output.
program trim_demo
implicit none
character(len=20) :: s = "hello"
print *, len(s)
print *, len_trim(s)
print *, "[" // trim(s) // "]"
end program trim_demo
Adjustl and adjustr
Adjustl moves text to the left and adjustr moves it to the right. Use them to align columns in reports without manual blank counting.
program adjust_demo
implicit none
character(len=20) :: s = "hello"
print *, "[" // adjustl(s) // "]"
print *, "[" // adjustr(s) // "]"
end program adjust_demo
Index and scan
Index finds the first occurrence of a substring and returns 0 when it is absent. Scan finds the first character from a set, which suits delimiter searches. Both return positions, not the text itself.
program find_demo
implicit none
character(len=32) :: line = "nx=200, tol=1.0e-8"
print *, index(line, "tol")
print *, scan(line, ",=")
end program find_demo
Verify sets
Verify checks that every character belongs to an allowed set and returns 0 when the string is clean. A nonzero result is the position of the first bad character. This makes it ideal for digit checks and input validation.
program verify_demo
implicit none
character(len=16) :: code = "20261006"
if (verify(code, "0123456789") == 0) write(*, "(a)") "digits only"
end program verify_demo
Next: Command-line arguments
Article author: Arthur Isaev