Format: add trailing spaces to character output to left-justify

前端 未结 5 1983
渐次进展
渐次进展 2021-01-06 11:34

How do you format a string to have constant width and be left-justified? There is the Aw formatter, where w denotes desired width of chara

相关标签:
5条回答
  • 2021-01-06 11:53

    I suggest that you do not limit the number of output characters.

    Change it to the following will work:

    44 format(A)
     print 44, 'Hi Stack Overflow'
    
    0 讨论(0)
  • 2021-01-06 11:57

    a bit ugly but you can concatenate a blank string:

        character*15 :: blank=' '
        print 44, 'Hi Stack Overflow'//blank
    
    0 讨论(0)
  • 2021-01-06 12:11

    To complete @francescalus excellent answer for future reference, the proposed solution also works in case of allocatables in place of string literals:

    character(len=:), allocatable :: a_str
    
    a_str = "foobar"
    
    write (*,"(A,I4)") a_str, 42
    write (*,"(A,I4)") [character(len=20) :: a_str], 42
    

    will output

    foobar  42
    foobar                42
    
    0 讨论(0)
  • 2021-01-06 12:13
    program test ! Write left justified constant width character columns 
    ! declare some strings.
    character(len=32) :: str1,str2,str3,str4,str5,str6 
    ! define the string values.
    str1 = "     Nina "; str2 = "       Alba  " ; str3 = "        blue   " 
    str4 = "  Jamil   "; str5 = "   Arnost "    ; str6 = " green             "
    write(*,'(a)') "123456789012345678901234567890"
    ! format to 3 columns 10 character wide each.
    ! and adjust the stings to the left.
    write(*,'(3(a10))') adjustl(str1), adjustl(str2), adjustl(str3) 
    write(*,'(3(a10))') adjustl(str4), adjustl(str5), adjustl(str6) 
    end program test
    
     $ ./a.out
    123456789012345678901234567890
    Nina      Alba      blue 
    Jamil     Arnost    green
    

    adjustL() moves leading spaces to the end of the string.

    0 讨论(0)
  • 2021-01-06 12:18

    As noted in the question, the problem is that when a character expression of length shorter than the output field width the padding spaces appear before the character expression. What we want is for the padding spaces to come after our desired string.

    There isn't a simple formatting solution, in the sense of a natural edit descriptor. However, what we can do is output an expression with sufficient trailing spaces (which count towards the length).

    For example:

    print '(A50)', 'Hello'//REPEAT(' ',50)
    

    or

    character(50) :: hello='Hello'
    print '(A50)', hello
    

    or even

    print '(A50)', [character(50) :: 'hello']
    

    That is, in each case the output item is a character of length (at least) 50. Each will be padded on the right with blanks.

    If you chose, you could even make a function which returns the extended (left-justified) expression:

    print '(A50)', right_pad('Hello')
    

    where the function is left as an exercise for the reader.

    0 讨论(0)
提交回复
热议问题