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

前端 未结 5 1972
渐次进展
渐次进展 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 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.

提交回复
热议问题