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

How to declare a character function

michael_green
Beginner
1,602 Views
I have written a small function called STRIM, very like TRIM, except that it also strips off traling null characters. In the function itself I have declared it as:

character*(*) function strim(string)

But how do I declare it in the calling routine? It works if I declare it as:

character*N strim

where N can be any integer, but of course I don't usually know what N is.

Is this the wrong approach? Any suggestions?

Many thanks
Mike
0 Kudos
4 Replies
alfredwodell
Beginner
1,602 Views
Why not just return the length of the new string?
E.g
print *, string(1:len_strim(string))
0 Kudos
Steven_L_Intel1
Employee
1,602 Views
TRIM is rather unusual - there is no good way to "write your own" function that does what it does. Alfred's suggestion is a good one.

Steve
0 Kudos
Jugoslav_Dujic
Valued Contributor II
1,602 Views
As the original poster discovered yourself, CHARACTER(*) functions do not do what one might think -- actually, they're a quirk in F9x and considered obsolete.

However, there is a way to do the similar as TRIM: in Fortran-95, length-specification-statements can be result of user-written PURE functions. Of course, entire thing needs an explicit interface, so it's best to place entire thing in a module:
MODULE Strings
!===========
CONTAINS
!===========
FUNCTION CTRIM(sStr)

CHARACTER*(*),INTENT(IN):: sStr
CHARACTER(LEN=CLEN(sStr)):: CTRIM

CTRIM = sStr

END FUNCTION CTRIM
!===========
PURE INTEGER FUNCTION CLEN(szString)

CHARACTER(*),INTENT(IN):: szString

CLEN = INDEX(szString,CHAR(0)) - 1
IF (CLEN==0) CLEN = LEN_TRIM(szString)

END FUNCTION CLEN
!===========
END MODULE Strings
Jugoslav

P.S. Actually, this is a field which caused many compilers to cough, especially when sizing expression is complex. This case is rather simple; CVF is hopefully mature enough to handle even more complex cases.
0 Kudos
rahzan
New Contributor I
1,602 Views
Even sleazier:

Function fullTrim(Input)
implicit none
Character(*),intent(in):: Input
integer(1) i
Character(Len_trim(Input)-verify(Input,' ')+1):: FullTrim
i=verify(Input,' ')
fullTrim=Input(i:)
end Function fullTrim
0 Kudos
Reply