开发者

Right justifying with printf

I've got a dictionary where both the keys and values are strings. I would like to print 开发者_如何学JAVAeach key-value pair on its own line with the key left justified and the value right justified.

Key1        Test
Key2    BlahBlah

Etc...

What's the best way to do this in PHP? Perhaps a clever way to do with printf?


Try this:

printf("%-40s", "Test");

The 40 tells printf to pad the string so that it takes 40 characters (this is the padding specifier). The - tells to pad at the right (this is the alignment specifier).

See the conversion specifications documenation.

So, to print the whole array:

$max_key_length = max(array_map('strlen', array_keys($array)));
$max_value_length = max(array_map('strlen', $array));

foreach($array as $key => $value) {
    printf("%-{$max_key_length}s   %{$max_value_length}s\n", $key, $value);
}

Try it here: http://codepad.org/ZVDk52ad


I'm not sure about PHP, but in C, the solution to right alignment is:

#include <stdio.h>
#include <math.h>
#include <stdio.h>

int main(){
  char *Data="hello world";
  printf("%20s\n",Data);
  return 0;
}

Output:

...$ ./a.out 
         hello world

You used to be able to do % 20s too, but in C that's deprecated now. Also, the other answer here is wrong %-20s will left align the text and space out to the right of the printed output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜