Character values and expressions

We can declare CHARACTER variables easily enough:

     CHARACTER :: X          ! X is one character
     CHARACTER(8) :: PHRASE  ! PHRASE is 8 characters long  
     CHARACTER(LEN=10) :: W  ! W is 10 characters long
     CHARACTER(4) :: A(8)    ! A is an array of CHARACTER(8) values

There are various operations we can do with CHARACTER data.

Assignment statements

Suppose we have some variables:

     CHARACTER(4) :: SHORT
     CHARACTER(8) :: LONG

If SHORT contains the value 'GHIJ' and we set LONG = SHORT, the result is that LONG will contain 'GHIJ '. That is, the value is copied in, left to right, and as it is not enough to fill LONG, the remaining bytes are padded with blanks.

On the other hand, if LONG contains the value 'RSTUVWXY' and we set SHORT = LONG, the result is that SHORT will contain 'RSTU'. That is, the value is truncated.

Padding and truncation occur on the right side of the value.

Concatenation

We can form one long CHARACTER value out of two smaller ones:

     'ABC'//'DEF' has the value 'ABCDEF'
     'X'//'Y'//'Z' has the value 'XYZ'

Substrings

Suppose I have a CHARACTER value such as

     CHARACTER(8) :: Word = 'HIGHWAYS'

and I only want part of it. I can manage this by using a substring: WORD(M:N) will be a CHARACTER value of length N - M + 1, containing characters from WORD starting at the Mth character and ending at the Nth character.

For example:

     WORD(2:3) is 'IG'
     WORD(1:5) is 'HIGHW'
     WORD(7:7) = 'Y'

If M is missing, we assume M = 1, and if N is missing, we assume N = the end of WORD. So:

     WORD(:6) is 'HIGHWA'
     WORD(6:) is 'WAY'

In particular, this means we can deal with a CHARACTER(N) variable almost as if it is an array of N individual characters. If we refer to WORD(M:M), we get just one character.

Search for a substring: INDEX

Suppose I have a CHARACTER(N) value, and I want to know if it contains 'ABC'. I can find out using the intrinsic function INDEX.

If S1 and S2 are CHARACTER values, INDEX(S1, S2) gives us the starting position of the first place at which S2 occurs inside S1, or 0 if it is never found. For example:

     INDEX('VANITY', 'NI') is 3
     INDEX('PUBLIC', 'L') is 4
     INDEX('MATHEMATICS', 'Q') is 0

What else?

There are several other intrinsic functions that deal with CHARACTER data.