问题
I need a portable function/subroutine to locate the position of the last non-blank character in a string. I've found two options: LEN_TRIM
and LNBLNK
. However, different compilers seem to have different standards. The official documentation for the following compilers suggests that LEN_TRIM is part of the Fortran 95 standard on the following platforms:
- IBM: LEN_TRIM
- Intel: LNBLNK and LEN_TRIM
- gfortran: LNBLNK and LEN_TRIM
- PGI: LEN_TRIM
However, it appears that nothing is guaranteed on compilers released before the F95 standard. My experience has been that older compilers might specify either LEN_TRIM
or LNBLNK
, but not necessarily both. My solution has been to use preprocessor conditionals:
#ifdef USE_LEN_TRIM
iNameLen = LEN_TRIM(cabase)
iExtLen = LEN_TRIM(caext)
#else
iNameLen = LNBLNK(cabase)
iExtLen = LNBLNK(caext)
#endif
and then pass -DUSE_LEN_TRIM
to the preprocessor. However, I am not a big fan of preprocessor conditionals & extra compile-time flags. Do you have any suggestions for a portable (before the Fortran 95 standard) function that locate the position of the last non-blank character in a string?
回答1:
LEN_TRIM is part of the Fortran 95 standard. I am not aware of any simple combination of intrinsics in Fortran 77 that could tackle this (TRIM also appeared with Fortran 95, and wasn't available in Fortran 77). But you can use a simple user function to perform that task if you really want to be portable without relying on compiler intrinsics and preprocessor:
function lentrim(s)
implicit none
character(len=*) :: s
integer lentrim
do lentrim = len(s), 1, -1
if (s(lentrim:lentrim) .ne. ' ') return
end do
end function lentrim
(tested with g77
and gfortran
; use option -ffree-form
to compile free-form source like this).
回答2:
Before the standard, I would say no. I've seen the len_trim function implemented by hand on F77 codes. If you want to be standard toward old compilers, then you will have to provide your own implementation as a failsafe, and use a preprocessor conditional to pick what you need.
回答3:
I'm stuck trying to find if this is a pre-Fortran 95 or not, but does
len(trim(s))
work?
来源:https://stackoverflow.com/questions/1257031/character-strings-in-fortran-portable-len-trim-and-lnblnk