I have to create a program that reverses phrases.
For example: when I write hello guys
, I want syug olleh
This is what
Unlike arrays, characters don't have advanced ways of selecting "elements": substrings must be contiguous (which in particular excludes "reverse order"). The approaches of other answers here follow from that: using expressions which individually select length-1 substrings to build up a new string. An example would be a simple loop selecting matching substrings.
If we construct an array from individual substrings we can use transfer to put the re-ordered elements back as a string.
Similar to an array constructor implied loop we can use an I/O implied loop with internal write:
implicit none
character(*), parameter :: string = 'abcde'
character(len(string)) :: reverse
integer i
write(reverse,'(*(A))') (string(i:i),i=len(string),1,-1)
write(*,'(A)') string, reverse
end
This approach, however, cannot be used "in-place" (unlike the transfer
one) as the internal file cannot appear in the I/O output item list. An intermediate variable could be used.