Using printf in C or Bash shell, how can I left- and right-justify two strings (character arrays) to a given length?
E.g. if the strings are “stack” and “overflow”, and the length is 20 characters, I wish to print
stack-------overflow
(for clarity, each space is shown as a dash).
The strings are of unknown length. If the total length + 1 exceeds the length given, is it possible to truncate one or both strings from either given direction and leave a space between them? E.g. if length is 10, can we get any of these?
stack-over
stack-flow
s-overflow
k-overflow
I know that printf(“%10s”, string) justifies one string to the right and printf(“%-10s”, string) justifies one string to the left, but can’t find a way to justify 2 strings, or to truncate them.
This is longer than battery’s, but imho it splits the strings better. Also it uses printf for truncation where possible, falling back to other mechanisms only for left-hand truncation of the second argument.
Bash:
C:
Sample output:
Disclaimer: The arithmetic can overflow, in which case the output will be wrong (or, if you can arrange for strlen(a)+strlen(b) to be exactly 2^64 bytes, the program will SIG_FPE). I can provide an explanation for the adj_a and adj_b computations if anyone cares.