Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two strings in Fortran

Here's an example in python3 of what I want to do in Fortran:

str1 = "Hello"
str2 = " World!"
print(str1 + str2)

# And then the result would be "Hello World!"

When I do:

print "(A)", str1, str2

It puts it on a separate line. If anyone knows how to help please answer.

like image 885
Prince Avatar asked Jan 05 '16 23:01

Prince


2 Answers

The literal answer to string concatenation, using the // operator, is given in another answer. Note, particularly, that you likely want to TRIM the first argument.

But there is another interesting concept your question raises, and that is format reversion.

With the format (A) we have one format item. In the output list str1, str2 we have two output items. In a general output statement we apply each format item (with repeat counts) to a corresponding output item. So, str1 is processed with the first format item A, and a string appears.

Come the second output item str2 we've already used the single format item, reaching the end of the format item list. The result is that we see this format reversion: that is, we go back to the first item in the list. After, crucially, we start a new line.

So, if we just want to print those two items to one line (with no space or blank line between them) we could use (neglecting trimming for clarity)

print "(A)", str1//str2

or we could use a format which hasn't this reversion

print "(2A)", str1, str2
print "(A, A)", str1, str2

The first concatenates the two character variables to give one, longer, which is then printed as a single output item. The second prints both individually.

Coming to your particular example

character(12), parameter :: str1="Hello"    ! Intentionally longer - trailing blanks
character(12), parameter :: str2=" World!"

print "(2A)", TRIM(str1), TRIM(str2)
end

will have output like

Hello World!

with that middle space because TRIM won't remove the leading space from str2. More widely, though we won't have the leading space there for us, and we want to add it in the output.

Naturally, concatenation still works (I'm back to assuming no-trimming)

character(*), parameter :: str1="Hello"    ! No trailing blank
character(*), parameter :: str2="World!"

print "(A)", str1//" "//str2
end

but we can choose our format, using the X edit descriptor, to add a space

print "(2(A,1X))", str1, str2
print "(A,1X,A)", str1, str2
print "(2(A,:,1X))", str1, str2

where this final one has the useful colon edit descriptor (outside scope of this answer).

like image 125
francescalus Avatar answered Oct 15 '22 03:10

francescalus


Probably close to what you want: Concatenate two strings in Fortran

zz = trim(xx) // trim(yy)

More info

Bing

like image 23
Kory Gill Avatar answered Oct 15 '22 04:10

Kory Gill