trim(str);len(str) /= len(trim(str))

trim(str);len(str) /= len(trim(str))


Why is there a difference in returned length between:

character(28) :: str='I-have-blanks-behind-me    '
l=len(string) ! => l=28


l=len(trim(string)) ! => l=23

and of course

l=len_trim(string)  ! => l=23

same situation for

l=index(string," ")  ! => l=24


l=index(trim(string)," ")  ! => l=0

This seems to be a bit inconsistent.
I am just curious why it is implemented this way.
It appears that during the assignment:


the string is padded with blanks. Is this Fortran standard?


Walter Kramer

3 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

OK, I am sorry. I should have thought before acting.

I understand that assigning a trimmed string to a string with a (longer) fixed length requires some form of padding. Padding with blanks seems the logical choice.

Walter Kramer

Yes, this is all standard. :-) The purpose of LEN is to return the total length of the string, including any trailing spaces. LEN_TRIM gives you the length without trailing spaces. As Fortran pads strings with spaces, it is nice to have both, one to tell you how much space you have available in the string variable, and another to tell you how much of that string variable is actually worth formatting.

The TRIM function returns a string of LEN_TRIM length of the original string, without the trailing spaces of course. But if you assign this back to the original string, the result will be the same as the TRIMmed string is space padded. So in your example, string=TRIM(string) does not change string, thus LEN(string) will not change either.


Leave a Comment

Please sign in to add a comment. Not a member? Join today