How to return a string without trailing spaces

How to return a string without trailing spaces

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!

Do few things, and do them well!
publicaciones de 9 / 0 nuevos
Último envío
Para obtener más información sobre las optimizaciones del compilador, consulte el aviso sobre la optimización.

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.

You can also do it with a function that returns a deferred-length allocatable character result.

Steve - Intel Developer Support

Cita:

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.

Do few things, and do them well!
Best Reply

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.

Steve - Intel Developer Support

Thank you, Steve!

Do few things, and do them well!

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.

Do few things, and do them well!

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*

Steve - Intel Developer Support

Thanks, again! "ifort" can behave properly, but "gfortran" still add the trailing spaces!

Do few things, and do them well!

Deje un comentario

Por favor inicie sesión para agregar un comentario. ¿No es socio? Únase ya