Jost
Jost

Reputation: 418

Fortran: Automatic determination of character length during initialization

In Fortran is it possible to automatically deduct the length of a character (string) when using an initializer during declaration? I want something like this (not working as it stands)

  character(*) :: a = 'John Doe'
  character(:) :: a = 'John Doe'

Example code

program char
  implicit none

  character(8) :: a = 'John Doe' !<-automatically?

  write(*,*) a
  write(*,*) len(a)

end program char

One correct way would be to use

  character(8) :: a = 'John Doe'

by simply counting the characters, which however is error-prone. Alternatively I could make the character longer than necessary and use trim()

program char
  implicit none

  character(100) :: a = 'John Doe'

  write(*,*) trim(a)
  write(*,*) len(trim(a))

end program char

But can the 8 be determined automatically? I am aware that this is an academic question, but I am still wondering...

Upvotes: 3

Views: 1542

Answers (3)

francescalus
francescalus

Reputation: 32396

Without using allocatable:

character(len=LEN_TRIM('John Doe') :: a = 'John Doe'

If you're worried about the repetition, a parameter can be used.

Of course, an allocatable character variable has its uses, and is quite likely suitable for you, but care must be taken if you really want the variable to retain its length through various assignments:

a(:) = 'J. Doe'

Upvotes: 1

High Performance Mark
High Performance Mark

Reputation: 78354

In addition to @AlexanderVogt's solution using parameter, you can also use automatic allocation in Fortran 2003, like this:

character(len=:), allocatable :: name

then initialise like this

name = 'John Doe'

and reset in the same way

name = 'John Doe Jr'

Upvotes: 5

Alexander Vogt
Alexander Vogt

Reputation: 18118

For parameters and dummy arguments you can use character(len=*):

program char
  implicit none

  character(100) :: a = 'John Doe'
  character(len=*),parameter :: b = 'John Doe'

  write(*,*) trim(a)
  write(*,*) len_trim(a), len(a)

  write(*,*) trim(b)
  write(*,*) len_trim(b), len(b)

end program char

This results in:

./a.out 
 John Doe
           8         100
 John Doe
           8           8

Upvotes: 2

Related Questions