2

I am studying about printf and sprintf and I don't understand a few points. Can someone please help me understand the following format specifiers explained at sprintf():

  • An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a - character here will make it left-justified.

  • An optional number, a width specifier that says how many characters (minimum) this conversion should result in.

4

2 に答える 2

7

幅指定子:

given:    printf('|%5d|', 1);
prints:   |    1|
           ^^^^^-- 4 spaces + 1 char = width of 5

アラインメント:

given:    printf('|%-5d|', 1);
prints    |1    |
           ^^^^^-- 1 char + 4 right-justified spaces = width of 5.
于 2012-06-12T14:47:25.217 に答える
2

Let's take a simple example:

<?php

$strs = "hello world";
printf("%-15s", $strs);
echo "\n";
printf("%15s", $strs);

?>

output:

hello world    
    hello world

^^^^^^^^^^^^^^^
|||||||||||||||
123456789012345  (width=15)

Here 15 is the minimum printed width of the string, and the - sign is to indent the string on the left.

于 2012-06-12T14:50:53.907 に答える