Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29235 Discussions

Removing trailing blanks from a string - not TRIM or ADJUSTR/L

IDZ_A_Intel
Employee
3,862 Views

Hi folks

Can someone shed some light on how to remove the trailing blanks from a character string please?

I thought TRIM would do the trick but that just counts the characters minus the trailing blanks - I want to keep the character string as a string, just without the blanks. UDJUSTR/L also seemed promising at first, but they simply move the blanks around and do not remove them.

I assume the apparent trouble I'm having with this is because a string, once declared as a particular size, cannot easily have its length changed (if at all???).

Thanks!

0 Kudos
4 Replies
Arjen_Markus
Honored Contributor II
3,862 Views

No, in Fortran (at least up to and including Fortran 95) a string has a fixed length. In Fortran 2003 you can define character strings with an allocatable length. An alternative is to use the iso_varying_length module (here is one version: http://www.fortran.com/iso_varying_string.f95, my Flibs project athttp://www.flibs.sf contains another implementation). This is mean to overcome the fixed length limitation of strings in Fortran 90/95.

Depending on what you want to do exactly, however, you can also use ordinary strings in this manner:

subroutine use_a_flexible_string( length )

character(len=length) :: string

...

end subroutine

This routine defines the length of the local variable string dynamically. The calling program determines what length to use.

Regards,

Arjen

0 Kudos
Arjen_Markus
Honored Contributor II
3,862 Views

Oops, the correct URL for Flibs is: http://flibs.sf.net

Regards,

Arjen

0 Kudos
rase
New Contributor I
3,862 Views

Take a look at John Burkhard's library pages, especially the chrpak collection:

(http://people.sc.fsu.edu/~burkardt/f_src/chrpak/chrpak.html).

Many subroutines do various tricks with character strings. Maybe you find there what you are looking for.

0 Kudos
Steven_L_Intel1
Employee
3,862 Views

As others have said, a normal character variable in Fortran has a fixed length. You can use TRIM when passing a string as an argument or in an expression, but if you assign the value to a variable you'll get the blanks back.

Intel Fortran 11.1 does support deferred-length allocatable character variables which I would recommend over the ISO_VARYING_STRING package. An example:

[fortran]character(:), allocatable :: str
str = 'abcde'
print *, len(str)  ! Prints 5
str = '123456789'
print *, len(str)  ! Prints 9
str = 'The Quick Brown Fox      '
str = trim(str)
print *, len(str)  ! Prints 19
end[/fortran]

0 Kudos
Reply