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!
9 帖子 / 0 全新
最新文章
如需更全面地了解编译器优化,请参阅优化注意事项

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

引文:

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!

发表评论

登录添加评论。还不是成员?立即加入