# 文字右对齐

27

``````Programming
Puzzles
&
Code
Golf
``````

``````Progr
ammin
g
Puzzl
es
&
Code
Golf
``````

``````Programmin
g
Puzzles
&
Code
Golf
``````

``````a

b
``````

``````    a
<-- note the 5 spaces
b
``````

1

Timwi's

Sp3000

@ sp3000可以有任何字符，包括空格。
Trebuchette

@Timwi：该示例每行只有一个单词。最好包含一些多字行，以明确一行中的空格不是特别的。（即只有换行符和非换行符。）
Peter Cordes

8

# Pyth，14个字节

``````jm.[\ QdscRQ.z
``````

10

## Python 2，84

``````s,n=input()
for w in s.split('\n'):
w=w or' '
while w:print w[:n].rjust(n);w=w[n:]
``````

8

# CJam，21个字节

``````li_qN/Sfe|f/ff{\Se[N}
``````

CJam解释器中在线尝试。

### 怎么运行的

``````li                     Read an integer L from the first line of input.
_                    Push a copy.
qN/                 Split the remaining input at linefeeds.
Sfe|             Map `OR " "'; the replaces empty lines with a space.
f/           Split each line into chunks of length L.
ff{     }  For each chunk, push L and the chunk; then:
\         Swap L with the chunk.
Se[      Left-pad the chunk to length L by prepending " ".
N     Push a linefeed.
``````

5

# 珀斯，16岁

``````jm>Q+*\ QdscRQ.z
``````

### 说明

``````jm>Q+*\ QdscRQ.z             : Q is the number on the first line, .z takes the rest
cRQ.z             : chop each line of .z into chunks of Q characters
m        s                  : remove nested lists and map over the result
+*\ Qd                   : add Q spaces to each line d
>Q                         : take the last Q characters of that result
j                            : join results on newlines
``````

4

# Perl，39个字节

``````perl -ni5 -e 's!^\$|.{1,\$^I}!printf"%\${^I}s
",\$&!ge'
``````

36个字节+ 3个字节（用于）`-ni`。换行宽度作为参数传递给`-i`

``````\$ echo -e "Programming\nPuzzles\n\n&\n\nCode\nGolf" | perl -ni5 -e 's!^\$|.{1,\$^I}!printf"%\${^I}s
",\$&!ge'
Progr
ammin
g
Puzzl
es

&

Code
Golf
``````

## 怎么运行的

``````^\$|.{1,\$^I}
``````

``````\$ echo -e "foo\n\nbar" | perl -ni2 -E 'say "<\$_>" for /^\$|.{1,\$^I}/g'
<fo>
<o>
<>
<ba>
<r>
``````

Dom Hastings

@DomHastings我从chilemagic那里学到了这个技巧，他在评论另一个挑战时提到了这一点。
ThisSuitIsBlackNotNot

3

# Javascript（ES6），107

``````(a,b)=>a.replace(eval(`/(.{\${b}})(?!\\n)/g`),`\$1
`).split`
`.map(c=>(Array(b).join` `+c).slice(-b)).join`
```````

``````(a, b)=>

// searches for sequences of characters longer than b without a newline after them and
// adds a newline after every b characters of the sequence
a.replace(eval(`/(.{\${b}})(?!\\n)/g`), '\$1\n')
.split('\n')
.map(c=>

// prepends b spaces to each string then slices it from the right down to length b
( Array(b).join(' ') + c ).slice(-b)

).join('\n')``````

3

# 朱莉娅126字节

``f(s,n)=for i=split(s,"\n") while length(i)>0 println(lpad(i[1:min(n,end)],n));length(i)<n?break:(i=i[min(n+1,end):end])end;end``

``````function f(s::String, n::Int)
for i in split(s, "\n")
while length(i) > 0
length(i) < n ? break : (i = i[min(n+1,end):end])
end
end
end``````

2

## 击，62，61 +特征，59

``````# width as a function arg: 59 chars
f()while read -rn\$1 r;do [[ \$r ]]&&printf %\$1s\\n "\$r";done
# width on stdin: 64 chars  (not updated with later suggestions&ideas)
``````

`read -n\$N`保存一个字符，但让`read`munge保留`\`

`[[ \$r ]]&&`因为需要`read -n4`不能前瞻地看到，下一个字符是一个换行符。因此将其设置`r`为4个字符的字符串，下一次读取将产生一个零字符的空字符串。筛选这些错误的换行而不筛选实际的换行将需要跟踪状态：前一行是否为max-length。要么需要更多代码，要么需要完全不同的方法。

`[[ \$r ]]``[ -n "\$r" ]`如果行以`-z foo`，或is 开头`*`（如果使用），则它比避免错误所需的长度短`[ \$r ]`

``````f()(while read -rn\$1 r;do [[ \$r ]]&&printf %\$1s\\n "\$r";done); (echo 4; echo -e "*\n\\"; cat /tmp/lines) | f 4
``````

1.我将包括`-r`在字节数中。2. `f()(while ... done)`要短一点。

@Dennis：如果不使用`[[ \$r ]]&&`，则如果N = 4，则长度为4的输入线将产生一条空白输出线，以前没有该线。由于`read`回报率的4个字符的字符串，然后看到下次调用和返回马上换行。另外，感谢您的`()`提示。我不知道您可以用这种方式定义fns。

Dennis

@丹尼斯：哇，哈克斯。感谢您的链接。其中一些对我来说是新鲜事物，我在另一个答案中修正了一些问题：)我通常不打高尔夫球，但是作为命令行迷的15年以上的经历教会了我一两个问题:)

2

``````import Data.List.Split
k[]=[""]
k x=x
f n=unlines.(map(\l->([1..n-length l]>>" ")++l).k.chunksOf n=<<).lines
``````

``````*Main> putStr \$ f 5 "a\n\nb\ncd\nMatamorphosis"
a

b
cd
Matam
orpho
sis
``````

``````                              .lines   -- split input string at newlines
=<<         -- for every line
chunksOf n           --    split into chunks of length n
k                      --    fix empty lines
map                                --    for every chunk
\l->([1..n-length l]>>" "      --      make a string of missing spaces
++l            --      and append the chunk
unlines                                -- join padded chunks with newlines in-between
``````

1

## GNU awk + ​​bash，70岁

``````f()(awk -vFPAT=.\{,\$1} '{for(i=0;i++<NF;){printf "%'\$1's\n",\$i}}/^\$/')
``````

`/^\$/`此处的规则是打印空行，这些行的NF = 0，因此在其他程序段中根本不打印。因此，与我的纯bash解决方案不同，这实际上在一般情况下都有效。

``````(echo 4; echo -e 'foo\nbar'; echo -e "*\n\\"; echo '~\$(true)'; cat /tmp/lines) |  # test input
perl -e '\$N=<>;\$/=\1;print "\$N\n"; while(<>){if(/\n/ or length(\$l)>=\$N){printf("%\$4s\n",\$l);\$l=/\n/?"":\$_;}else{\$l.=\$_;}}'
``````

1

# Bash + GNU utils，41

``````fold -\$1|sed ":;s/^.\{,\$[\$1-1]\}\\$/ &/;t"
``````

``````ubuntu@ubuntu:~\$ echo 'Programming
Puzzles
&
Code
Golf'|./ralign.sh 10
Programmin
g
Puzzles
&
Code
Golf
ubuntu@ubuntu:~\$
``````

1

# Python 2，151字节

``````s,n=input();N='\n'
for w in[i.lstrip()if i.replace(' ','').isalpha()else i for i in s.replace(N,'\n ').split(N)]:
while w:print w[:n].rjust(n);w=w[n:]
``````

`for`循环由改变：

``````for w in s.split('\n'):
``````

``````for w in[i.lstrip()if i.replace(' ','').isalpha()else i for i in s.replace(N,'\n ').split(N)]:
``````

# 例

``````\$ python main.py
"Programming\n\n\nPuzzles\n\n&\n\nCode\nGolf", 5
Progr
ammin
g

Puzzl
es

&

Code
Golf
``````

1

# C＃，143个字节

``````(s,n)=>Join("\n",s.Split('\n').SelectMany(l=>(l.Any()?l:" ").Select((c,i)=>new{c,i}).GroupBy(o=>o.i/n,o=>o.c).Select(g=>Concat(g).PadLeft(n))))
``````

Linq使您可以做出漂亮的表情。`GroupBy`在这里很有用，但是很遗憾他们无法创建使用索引的函数重载。

``````Func<string, int, string> Align = (s, n) => Join("\n",
s.Split('\n')
.SelectMany(l => (l.Any() ? l : " ")
.Select((c, i) => new { c, i })
.GroupBy(o => o.i / n, o => o.c)
``````

1

# Groovy，63个字节

``````f={s,n->s.split("(?<=\\G.{\$n})|\n")*.padLeft(n," ").join("\n")}
``````

1

# 的JavaScript 174 136

``````function R(s,x){return s.replace(new RegExp(".{"+x+"}","g"),"\$&\n").replace(/[^\n]*/g,function(m){
while(m.length<x)m=" "+m;return m;})}
``````

1

# 锡兰，107

``````String w(String s,Integer n)=>"\n".join{for(l in s.lines)for(p in l.partition(n))String(p).padLeading(n)};
``````

1

# Matlab，99个字节

``````@(s,k)fliplr(char(cellfun(@fliplr,strsplit(regexprep(s,sprintf('\\S{%i}',k),'\$0\n'),'\n'),'un',0)))
``````

``````>> @(s,k)fliplr(char(cellfun(@fliplr,strsplit(regexprep(s,sprintf('\\S{%i}',k),'\$0\n'),'\n'),'un',0)))

ans =

@(s,k)fliplr(char(cellfun(@fliplr,strsplit(regexprep(s,sprintf('\\S{%i}',k),'\$0\n'),'\n'),'un',0)))

>> ans(['Programming' 10 'Puzzles' 10 '&' 10 'Code' 10 'Golf'], 5) %% 10 is line feed

ans =

Progr
ammin
g
Puzzl
es
&
Code
Golf
``````

1

## 滑稽，28字节

``````lng_riPpun{pPco{pP' lp}mu}Wl
``````

``````\$ cat input.txt | blsq --stdin "lng_riPpun{pPco{pP' lp}mu}Wl"
Progr
ammin
g
Puzzl
es
&
Code
Golf
``````

``````{5co{5' lp}mu}Wl
``````

``````blsq ) "Programming\nPuzzles\n&\nCode\nGolf"{5co{5' lp}mu}Wl
Progr
ammin
g
Puzzl
es
&
Code
Golf
``````