Search code examples
stringfortrancharacter

How to check if character is upper or lowercase in Fortran?


Within Fortran, what are the library functions, if any (I'm using gfortran 11) that return whether the character is upper or lower case?

character :: c
c = 'l'
print *, is_lower(c) ! should display 'T'
print *, is_upper(c) ! should display 'F'
c = 'L'
print *, is_upper(c) ! should display 'T'

What should I be using in place of is_lower and is_upper? I can try to roll my own, but the comparison operators are weird enough with characters that I can't be sure of exactly what I'm doing.


Solution

  • Thanks to @High Performance Mark's help, I have this hacky way of doing the checking for each character:

    module char_cases
      implicit none
    
      private
      public :: is_upper_ascii, is_lower_ascii
    
      character(len=26), parameter :: uca = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      character(len=26), parameter :: lca = 'abcdefghijklmnopqrstuvwxyz'
    
    contains
    
      pure elemental logical function is_upper_ascii(ch)
        character, intent(in) :: ch
        is_upper_ascii = index(uca, ch) /= 0
      end function is_upper_ascii
    
      pure elemental logical function is_lower_ascii(ch)
        character, intent(in) :: ch
        is_lower_ascii = index(lca, ch) /= 0
      end function is_lower_ascii
    
    end module char_cases