| Bytes | Lang | Time | Link |
|---|---|---|---|
| 049 | AWK | 241205T184410Z | xrs |
| 041 | Perl 5 | 240528T015519Z | Xcali |
| 043 | Powershell | 230429T162050Z | spookyco |
| 110 | Go | 230501T132358Z | bigyihsu |
| 212 | brainfuck | 230501T034345Z | ATaco |
| 086 | C gcc | 230429T164830Z | evanstar |
| 005 | Japt | 230429T235918Z | noodle p |
| 008 | Vyxal | 230429T222324Z | lyxal |
| 034 | Arturo | 230429T215849Z | chunes |
| 038 | Lua | 230429T185105Z | bluswimm |
| 034 | JavaScript ES6 | 161011T105455Z | Huntro |
| 050 | R | 161011T100851Z | Billywob |
| 048 | PHP | 160526T084714Z | aross |
| 057 | Bash | 160331T223015Z | philcolb |
| 016 | JavaScript ES7 | 160526T013940Z | Downgoat |
| 038 | JavaScript ES6 | 160424T011549Z | Conor O& |
| 088 | Java 8 | 160403T010745Z | hyperneu |
| 042 | Ruby | 160401T213245Z | jose_cas |
| 012 | Jelly | 160330T055500Z | Dennis |
| 035 | Javascript ES6 | 160328T030335Z | David |
| 070 | JavaScript ES5 | 160324T161727Z | rjmunro |
| 013 | Mathematica | 160324T163743Z | Calculat |
| 043 | JavaScript ES6 | 160324T105747Z | Neil |
| 064 | C | 160324T154542Z | Cole Cam |
| 012 | Pyke | 160324T174128Z | Blue |
| 055 | Javascript ES6 | 160324T180947Z | pllee |
| 004 | Julia | 160324T190439Z | Fengyang |
| 041 | Python | 160324T170344Z | Valentin |
| 067 | Pike | 160324T142510Z | cat |
| 009 | 05AB1E | 160324T150533Z | Adnan |
| 029 | Python 3 | 160324T140923Z | cat |
| 011 | Pyth | 160324T120138Z | Doorknob |
| 044 | JavaScript ES6 | 160324T104419Z | Sklivvz |
AWK, 49 bytes
$0=gensub(/ /,$3?$3:" ","g",sprintf("%*s",$2,$1))
$0= # set ouput
gensub(/ /, # sub spaces for $3
$3?$3:" ","g", # or spaces if no $3
sprintf("%*s",$2,$1)) # pretty print
Powershell, 87 67 incorrect counted 54, 46 43 Bytes
$f={param($s,$l,$c='')$c*($l-$s.length)+$s}
Go, 110 bytes
import."strings"
func l(n int,c...string)string{q,p:=c[0]," "
if len(c)>1{p=c[1]}
return Repeat(p,n-len(q))+q}
Uses Go's variadic arguments feature to have an optional argument. Expects at minimum 1 string passed to the function (the string to be padded); the first string after that is the padding character.
A solution were all arguments are explicit is significantly shorter:
Go, 76 bytes, no variadic arguments
import."strings"
func l(s,c string,n int)string{return Repeat(c,n-len(s))+s}
brainfuck, 212 bytes
,----------[++++++++++<[<]<+>>[>],----------]<[<]<<<,----------[<[-<++++++++++>]<[->+<]>>>++++++++[-<----->]<++[-<+>],----------]>>[-<<<->>>]++++[>++++++++<-]><<+>,[<->[-<<+>>]]<[->>[-<<<+>>>]<<]<<[->.<]>>>>>[.>]
Explained
,----------[ While it isn't a newline
++++++++++ Restore the character
<[<]<+>>[>] Increment the counter behind the array and return
,----------] Read and repeat
<[<]<<< navigate behind the length
,----------[ While it isn't a newline
<[-<++++++++++>]<[->+<]>> x10 the stored number
>++++++++[-<----->]<++ sub 39
[-<+>] Copy into stored
,----------] Read and repeat
>>[-<<<->>>] Subtract the counter from the target
++++[>++++++++<-]> Prepare a space
<<+>,[<->[-<<+>>]] If the next byte isnt eof then we copy it left two and zero the test byte
<[->>[-<<<+>>>]<<] If the text bit is still high copy space in there instead
<<[->.<] While the counter is positive write the pad char
>>>>>[.>] Write the rest of the string
Arguments separated by linefeeds. If no pad char is present, a linefeed after the length must still be included.
C (gcc), 91 86 bytes
Takes 2 or 3 arguments on the command line. Also uses the rare "-->" operator!
-5 bytes from ceilingcat and c--
l;main(c,v)int**v;{for(l=atoi(v++[2]);l-->strlen(*v);)putchar(c-3?*v[2]:32);puts(*v);}
Japt, 5 bytes
ùVWªS
ù # left-pad the input string with:
V # second input (length)
WªS # third input, or space if not specified
Or, for 1 byte:
ù
But this isn't a full program, so I don't think it counts. It can be called AùBC where A is the string, B is the length, and C is (optionally) the padding character.
Vyxal, 8 bytes
□ðJ3Ẏ÷ø↳
Link is to test suite. Somehow, vyncode also gives 8 bytes.
Explained
□ðJ3Ẏ÷ø↳
□ðJ # append a space to all input arguments
3Ẏ # take the first 3 items of that
÷ # dump everything to the stack
ø↳ # call the built-in left pad function.
JavaScript (ES6), 34 bytes
I used a recursive solution.
f=(s,l,c=' ')=>s[l-1]?s:f(c+s,l,c)
R, 50 bytes
Late to the party again but here it goes:
function(s,n,p=" ")cat(rep(p,n-nchar(s)),s,sep="")
This simply prints the output to stdout but does not actually return the padded string (wasn't sure if this is a requirement for the challenge). If this is needed, the solution is slightly longer at 61 bytes:
function(s,n,p=" ")paste0(c(rep(p,n-nchar(s)),s),collapse="")
PHP, 54 48 bytes
Uses Windows-1252 encoding.
function(&$s,$l,$p=~ß){$s=str_pad($s,$l,$p,0);};
Run like this (-d added for easthetics only):
php -r '$f = function(&$s,$l,$p=~ß){$s=str_pad($s,$l,$p,0);}; $s="foo";$f($s,5);echo"$s\n";' 2>/dev/null
Old version (without the builtin):
function(&$s,$l,$p=~ß){for(;strlen($s)<$l;)$s=$p.$s;};
Tweaks
- Saved 6 bytes by using
str_padinstead of a loop. Leaving the old one for reference, as builtins are frowned upon
Bash, 57 Bytes
Parameters: string width padchar
printf -vX %$2s;Y="${X// /${3- }}$1";echo -n "${Y:${#1}}"
Make a string of width spaces.
Convert each space character into padchar.
Write padding then string.
JavaScript ES7, 16 bytes
''.padStart.bind
built-ins ftw! Only works on Firefox 48 and above. Valid as this feature was added March 12.
This takes input like:
(''.padStart.bind)(arg1)(arg2,arg3)
JavaScript ES6, 38 bytes
(s,l,c=" ")=>(c.repeat(l)+s).slice(-l)
An alternate solution.
Java 8, 86 88 bytes
This is a function. The third argument is a varargs to allow the optional pad char (defaults to ' ')
String p(String s,int l,char...p){return s.length()<l?p((p.length>0?p[0]:' ')+s,l,p):s;}
Recursion! +2 bytes (added brackets because of incompatible type error)
Ruby, 42 bytes
def left_pad(s,t,p=" ");p*(t-s.size)+s;end
Parameters: string, size, padchar.
Test suite below; should print all "true"s, just put everything in the same file.
puts left_pad("foo", 5) == " foo"
puts left_pad("foobar", 6) == "foobar"
puts left_pad("1", 2, "0") == "01"
puts left_pad("1", 2, "-") == "-1"
Jelly, 12 bytes
L⁴_ẋ@⁵⁵⁶<?¤³
So many variable references. Wasn't Jelly supposed to be a tacit language?
How it works
L⁴_ẋ@⁵⁵⁶<?¤³ Main link
Arguments: string (³), length (⁴), padchar (⁵, defaults to 10)
L Compute the length of ³.
⁴_ Subtract the length from ⁴.
¤ Combine the two links to the left into a niladic chain:
⁵ Yield ⁵.
⁵⁶<? Yield ⁵ if ⁵ < ⁵, else ⁶.
Comparing a number with itself gives 0 (falsy), but comparing a
string / character list with itself gives [0] (truthy).
ẋ@ Repeat the result to the right as many times as specified in the
result to the left.
³ Print the previous return value and return ³.
Javascript ES6, 35 bytes
(s,l,c=' ')=>c.repeat(l-s.length)+s
Try it. I believe this is the shortest possible implimentation currently possible in Javascript.
JavaScript (ES5), 70 bytes
Using recursion...
function f(s,c,p,u){return(s+'').length<c?f((p==u?' ':p+'')+s,c,p):s}
My initial go was only 57 bytes:
function f(s,c,p){return s.length<c?f((p||" ")+s,c,p):s}
But only passed the first 2 tests:
> f('foo', 5) === ' foo';
true
> f('foobar', 6) === 'foobar';
true
> f(1, 2, 0) === '01';
false
> f(1, 2, '-') === '-1';
false
I still like the shorter one, because in practise, passing numbers to a string manipulation function isn't a feature I would need.
Mathematica, 13 bytes
StringPadLeft
Builtin-only answer #3 (first was Range, second was Surd)
Or less builtin: (35 bytes)
##2~StringRepeat~(#3-Length@#2)<>#&
JavaScript (ES6), 43 bytes
f=(s,n,p=" ",r=p)=>(r+=s+="")[n]?s:f(r,n,p)
Pyke, 12 bytes (noncompeting)
added input node, bugfix on len node, change default results on assign node after the challenge was posted.
\ =zzjl-z*j+
Explanation:
\ =z - assign default input for `z` to be " " (Will still prompt but no input will return a space instead)
zj - j = input()
l - len(j)
- - eval_or_not_input() - ^
z* - ^*input()
j+ - ^+j
Javascript (ES6), 55 bytes
(a,n,c=' ',s=a+'')=>(new Array(++n-s.length).join(c)+s)
Create an empty array of values and join version.
(a,n,c=' ')=>{a+=''; return new Array(++n-a.length).join(c)+a}
Is more readable but the return adds a few more characters.
Julia, 4 bytes
lpad
Passes all the test cases:
julia> lpad("foo", 5)
" foo"
julia> lpad("foobar", 6)
"foobar"
julia> lpad(1, 2, 0)
"01"
julia> lpad(1, 2, '-')
"-1"
Python, 41 bytes
lambda a,b,x=' ':str(a).rjust(b,str(x))
Without the builtin rjust, 43 bytes:
lambda a,b,x=' ':str(x)*int(b/2%3)+str(a)
(not what one expects it to do, but it passes the test suite)
Pike, 67 bytes
mixed n(mixed a,int b,mixed x){return x!=""?x:" "*(b-strlen(a))+a;}
sigh. The empty string "" evaluates to true. Why!?
mixed mixed mixed mixed mixed Pike soup...
05AB1E, 11 9 bytes
Code:
g-ð³0@×¹«
Explanation:
g # Implicit first input, take the length.
- # Substract the length with the second input.
ð³ # Push a space and if the third input exists, also the third input.
0@ # Reposition the first element of the stack to the top (zero-indexed).
× # Multiply the character with the difference in length.
¹« # Concatenate the first input to the string.
Uses CP-1252 encoding. Try it online.
Python 3, 33 31 29 bytes
lambda a,b,x=" ":a.rjust(b,x)
Fairly straightforward. Thanks to @xnor for reminding me str.rjust is a thing. :P
For the same length (also thanks to xnor):
lambda a,b,x=" ":(x*b+a)[-b:]
Previous solution:
lambda a,b,x=" ":x*(b-len(a))+a
Pyth, 13 11 bytes
+*.xwd-Qlzz
Takes input from STDIN as the string on the first line, length on the second line, and padding char optionally on a third line.
JavaScript (ES6), 37 43 44 bytes
(a,n,c=' ')=>((c+'').repeat(n)+a).substr(-n)
Test:
> f=(a,n,c)=>((c?c:" ").repeat(n)+a).substr(-n)
< function (a,n,c)=>((c?c:" ").repeat(n)+a).substr(-n)
> f('foo', 5) === ' foo';
< true
> f('foobar', 6) === 'foobar';
< true
> f(1, 2, 0) === '01';
< true
> f(1, 2, '-') === '-1';
< true
Not sure if you want to count the function declaration, I'd inline this.