Search code examples
textfortrancharactertrimfortran77

How do I TRIM a character array in standard F77?


I'm reading from ASCII data files with text headers. (The headers contain info about the data run.) I want to add some of the columns of each data file, then write the result to another data file, but keep the headers for each of the files. The problem is, I don't know beforehand what the lengths of the header lines are. If I use a long character variable (character*400, for example) to make sure I get the entire header lines, then my new data files have lots of white space I don't want. Basically, I want to do TRIM(HeaderVariable), but TRIM is not available to me. Any suggestions? Is there a way to WRITE only to a CrLF? I thought of using an array of character*1, and testing each character as I read it and write it, but...wow, that's sooooo complicated. Is there a simpler way to do this in standard F77? [edit: self-answer moved to answer. could not do it at first because rep was too low.]


Solution

  • I got the answer. Posting here to help others. The LENGTH function below is taken from http://www.star.le.ac.uk/~cgp/prof77.html#tth_sEc7 Once you've got this LENGTH function, it's trivial to implement your own TRIM function. Functionally, this isn't much different from my initial horrid idea, but it's prettier.

    LEN The LEN function takes a character argument and returns its length as an integer. The argument may be a local character variable or array element but this will just return a constant. LEN is more useful in procedures where character dummy arguments (and character function names) may have their length passed over from the calling unit, so that the length may be different on each procedure call. The length returned by LEN is that declared for the item. Sometimes it is more useful to find the length excluding trailing blanks. The next function does just that, using LEN in the process.

        INTEGER FUNCTION LENGTH(STRING) !Returns length of string ignoring trailing blanks 
        CHARACTER*(*) STRING 
        DO 15, I = LEN(STRING), 1, -1 
          IF(STRING(I:I) .NE. ' ') GO TO 20 
    15  CONTINUE 
    20  LENGTH = I 
        END