You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Fortran(gfortran 11)中判断字符的大小写?

在gfortran 11中判断字符大小写的方法

Fortran标准库没有直接提供is_lower或is_upper这类函数,但你可以通过两种可靠的方式实现需求,完全适配gfortran 11的环境:

方法1:直接利用字符范围比较

gfortran默认采用ASCII编码,而ASCII中大小写字母分别是连续的字符区间(小写a-z对应字符值97-122,大写A-Z对应65-90),直接用字符比较运算符即可判断:

program test_case
    implicit none
    character :: c

    c = 'l'
    print *, is_lower(c)  ! 输出 T
    print *, is_upper(c)  ! 输出 F
    c = 'L'
    print *, is_upper(c)  ! 输出 T

contains
    logical function is_lower(c)
        character, intent(in) :: c
        is_lower = (c >= 'a' .and. c <= 'z')
    end function is_lower

    logical function is_upper(c)
        character, intent(in) :: c
        is_upper = (c >= 'A' .and. c <= 'Z')
    end function is_upper
end program test_case

方法2:通过字符转编码值判断

如果想更明确地依赖ASCII编码规则,可以用ichar函数将字符转换为对应的ASCII整数,再判断区间:

program test_case
    implicit none
    character :: c

    c = 'l'
    print *, is_lower(c)  ! 输出 T
    print *, is_upper(c)  ! 输出 F
    c = 'L'
    print *, is_upper(c)  ! 输出 T

contains
    logical function is_lower(c)
        character, intent(in) :: c
        integer :: char_code
        char_code = ichar(c)
        is_lower = (char_code >= ichar('a') .and. char_code <= ichar('z'))
    end function is_lower

    logical function is_upper(c)
        character, intent(in) :: c
        integer :: char_code
        char_code = ichar(c)
        is_upper = (char_code >= ichar('A') .and. char_code <= ichar('Z'))
    end function is_upper
end program test_case

两种方法在gfortran 11下都能稳定运行,因为gfortran默认的字符编码是ASCII,字符比较和ichar的行为完全符合预期,不用担心运算符的可靠性问题。

内容的提问来源于stack exchange,提问作者rigel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 06:09:50