How can I write a to_upper() or to_lower() function in F90?

后端 未结 3 2493
深忆病人
深忆病人 2021-02-19 21:11

How does one write a (Intel) F90 function that converts a string into lowercase (or, alternatively, uppercase)? I want to pass a character array to the function and have it retu

3条回答
  •  清歌不尽
    2021-02-19 21:25

    Here's one that doesn't rely on the ASCII representation

    Pure Function to_upper (str) Result (string)
    
    !   ==============================
    !   Changes a string to upper case
    !   ==============================
    
        Implicit None
        Character(*), Intent(In) :: str
        Character(LEN(str))      :: string
    
        Integer :: ic, i
    
        Character(26), Parameter :: cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        Character(26), Parameter :: low = 'abcdefghijklmnopqrstuvwxyz'
    
    !   Capitalize each letter if it is lowecase
        string = str
        do i = 1, LEN_TRIM(str)
            ic = INDEX(low, str(i:i))
            if (ic > 0) string(i:i) = cap(ic:ic)
        end do
    
    End Function to_upper
    

    You can easily change this to to_lower by switching the low and cap strings in the loop.

提交回复
热议问题