Dynamic strings in Fortran

So dynamic strings in Fortran are a little different. Don’t forget, there are character strings and character arrays. They are different, and so have to be treated different when it comes to dynamic memory, and dynamic strings can be tricky. Issue #1: dynamic strings cannot be read directly using  read. So a buffer i needed.

 character (len=256) :: buffer
 character (len=:), allocatable :: str

The first declaration creates a buffer string with a max of 256 characters. The second declaration creates an allocatable dynamic string. Now we can read an ASCII string into buffer in the following manner:

read(*,'(A)') buffer

Now we can assign this to the dynamic string, with the system automatically reserving memory internally.  Two string handling functions are used to process the sting: adjustl() left-justifies the text and removes leading spaces, and trim() removes trailing spaces.

str = trim(adjustl(buffer))

Now to add to that string is a case of using the Fortran concatenation operator: //. Concatenation is performed by placing one string after another. Here’s an example:

str = str // " " // trim(adjustl(buffer))

This also adds a space between strings. Note that deferred-length strings occur in Fortran 2003 onwards, so compile using gfortran -std=f2003.

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s