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

How to return a string without trailing spaces

Li_Dong
Beginner
953 Views

Dear all,

I would like to write a function that will return a string, but I do not want the string contains trailing spaces. How could I do it? Thanks!

0 Kudos
1 Solution
Steven_L_Intel1
Employee
953 Views
function foo() character(:), allocatable :: foo foo = "abc" end function foo You must have an explicit interface for this visible to the caller - the easiest way to do that is to put the function in a module and then USE the module in the program units where you want to call the function. Please note also that you need a reasonably current compiler (12.1 minimum, I think), for this to work.

View solution in original post

0 Kudos
8 Replies
JVanB
Valued Contributor II
953 Views
You could write a specification function that computes the length of the function result. Sometimes this isn't feasible, though, for example when the function returns the next line of input. In this case the function result may be declared as allocatable length. In either case the interface must be explicit in the calling program unit.
0 Kudos
Steven_L_Intel1
Employee
953 Views
You can also do it with a function that returns a deferred-length allocatable character result.
0 Kudos
Li_Dong
Beginner
953 Views
You can also do it with a function that returns a deferred-length allocatable character result.
Can you give me an example solution of this: character(1000) function foo() foo = "abc" end function foo where I would like foo() to return "abc", not "abc" with huge number of spaces.
0 Kudos
Steven_L_Intel1
Employee
954 Views
function foo() character(:), allocatable :: foo foo = "abc" end function foo You must have an explicit interface for this visible to the caller - the easiest way to do that is to put the function in a module and then USE the module in the program units where you want to call the function. Please note also that you need a reasonably current compiler (12.1 minimum, I think), for this to work.
0 Kudos
Li_Dong
Beginner
953 Views
Thank you, Steve!
0 Kudos
Li_Dong
Beginner
953 Views
I am still having a problem as: function foo() character(:), allocatable :: foo character(1000) bar bar = "abc" foo = trim(bar) end function foo The content of foo still includes trailing spaces.
0 Kudos
Steven_L_Intel1
Employee
953 Views
I tried it and it worked correctly for me. Here's the test program I used and its output: print '(A,A,A)', '*',foo(),'*' contains function foo() character(:), allocatable :: foo character(10) bar bar = "abc" foo = trim(bar) end function foo end *abc*
0 Kudos
Li_Dong
Beginner
953 Views
Thanks, again! "ifort" can behave properly, but "gfortran" still add the trailing spaces!
0 Kudos
Reply