Aligning Lines!
APL (37)
APL just isn't very good at string processing (or I'm not good at golfing, of course).
{⌽∊R,¨' '/⍨¨(⌈/-+)⍺⍳⍨¨⌽¨R←S⊂⍨S=⊃S←⌽⍵}
This takes the character as its left argument, and the multiline string as its right argument. It is assumed that the multiline string ends in a linefeed (e.g. A\nB\nC\n
rather than A\nB\nC
.) Since I can use "any format [I] wish", and this is also the conventional format for text files, I think this is reasonable.
Explanation:
S←⌽⍵
: reverse the string, and store it inS
.R←S⊂⍨S=⊃S
: splitS
on its first character, and store the array of strings inR
.⍺⍳¨⌽¨R
: reverse each string inR
, and then find the index of ⍺ (the character) in each string.(⌈/-+)
: subtract each of the indices from the largest index, giving the amount of spaces needed' '/⍨¨
: for each of those values, generate that many spacesR,¨
: add the spaces to each string inR
.∊
: join all the strings together⌽
: reverse it (to get the original order back)
Example:
NL←⎕UCS 10 ⍝ newline
test←'Programming, Puzzles',NL,'And, Code golf',NL
test ⍝ test string
Programming, Puzzles
And, Code golf
⍝ run the function
+X←','{⌽∊R,¨' '/⍨¨(⌈/-+)⍺⍳⍨¨⌽¨R←S⊂⍨S=⊃S←⌽⍵}test
Programming, Puzzles
And, Code golf
⍴X ⍝ result is really a string with newlines, not a matrix
44
CJam, 23 22 20 bytes
Thanks to Dennis for saving 2 bytes.
ea_rf#_:e>\fm.{S*\N}
This reads the lines from command-line arguments and the character from STDIN.
The online interpreter doesn't support command-line arguments, but you can test an equivalent version here.
Explanation
ea e# Get the lines from ARGV.
_rf# e# Duplicate input, read the character and find index of character in each line.
_:e> e# Duplicate indices and find maximum.
\fm e# Subtract each index from the maximum index.
.{ e# Apply this block to each pair of line and (max_index - index).
S* e# Get a string with the right amount of spaces.
\N e# Swap spaces with line and push a line feed.
}
Pip, 22 20 18 + 1 = 19 bytes
Y_@?qMgsX(MXy)-y.g
Takes strings as command-line arguments and delimiter from STDIN (idea borrowed from Martin's CJam answer). Uses -n
flag to print output values on separate lines.
g is list of cmdline args; s is space (implicit)
q Read the delimiter from stdin
_@? Construct a lambda function that takes a string and returns
the index of the delimiter in it
Mg Map that function to each remaining item in g
Y Yank the resulting list of indices into the variable y
(MXy)-y Take the max of y minus each element in y
sX Space, repeated that many times...
.g ... concatenated to each item in g
Print, newline-separated (implicit, -n flag)
And an example run:
C:\Users\dlosc> pip.py -ne Y_@?qMgsX(MXy)-y.g "Programming, Puzzles" "And, Code golf"
,
Programming, Puzzles
And, Code golf