How to reverse a chain of characters?

后端 未结 5 1547
野的像风
野的像风 2021-01-24 18:24

I have to create a program that reverses phrases.

For example: when I write hello guys, I want syug olleh

This is what

5条回答
  •  醉话见心
    2021-01-24 19:12

    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.

提交回复
热议问题