# Multiply a string by a number!

There was a challenge up a while ago about multiplying strings. It showed us how we can multiply not only numbers, but also strings. However, we still can't multiply a number by a string properly. There has been one attempt to do so but this is obviously wrong. We need to fix that!

Write a function or program that multiplies two inputs, a string and an integer. To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string. If the input is 0, output nothing (anything multiplied by 0 equals nothing).

## Input:

A string that consists solely of printable ASCII characters and newlines, and an integer (possible negative).

## Output:

The string multiplied by the integer.

## Examples:

Hello World!, 3            --> HHHeeellllllooo   WWWooorrrlllddd!!!
foo, 12                    --> ffffffffffffoooooooooooooooooooooooo
String, -3                 --> gggnnniiirrrtttSSS
This is a fun challenge, 0 -->
Hello
World!, 2                  --> HHeelllloo

WWoorrlldd!!


## Scoring:

This is , lowest byte count wins!

• Can we assume the string is printable ASCII-only, plus newlines? Jul 11, 2017 at 21:45
• Can we output a list of strings? Jul 11, 2017 at 21:50
• Partial solution in Retina. Only works for positive values of the integer. I probably won't make time to finish it if someone wants to. tio.run/##K0otycxL/P8/… Jul 11, 2017 at 21:59
• @mbomb007, yes, sorry for taking so long about that. Aug 2, 2017 at 0:08
• @totallyhuman, no you may not. Aug 8, 2017 at 3:52

# Jelly, 65 4 bytes

²Ɠxm


Try it online!

### How it works

²Ɠxm  Main link. Argument: n (integer)

²     Yield n².
Ɠ    Read and eval one line of input. This yields a string s.
x   Repeat the characters of s in-place, each one n² times.
m  Takes each |n|-th character of the result, starting with the first if n > 0,
the last if n < 0.

• OK, now I'm really impressed. I'd love an explanation of this particular wonder in miniature. Jul 11, 2017 at 21:12
• Sure. As soon as I made a test suite and am done golfing. Jul 11, 2017 at 21:18
• OK, if you can make this any smaller, I'm going to give up trying to make a question that will take you >10 bytes. Jul 11, 2017 at 21:19
• OK, that's it. I'm learning Jelly. I want to be able to do magic too. Jul 11, 2017 at 21:31
• We all know how a discussion about Jelly chains ends up being a mess... Jul 12, 2017 at 9:11

## JavaScript (ES6), 63 bytes

Takes input in currying syntax (s)(n).

s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')


### Test cases

let f =

s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')

console.log(f(Hello World!)(3))
console.log(f(foo)(12))
console.log(f(String)(-3))
console.log(f(This is a fun challenge)(0))
console.log(f(Hello
World!)(2))

• +1 for reduce!
– Neil
Jul 11, 2017 at 22:46

# Python 3, 44 bytes

f=lambda s,n:s and s[0]*n+f(s[1:],n)+s[0]*-n


Try it online!

• The base case seems to ignore the last character.
– xnor
Jul 11, 2017 at 21:45
• Not quite sure why I did that... Thanks! Jul 11, 2017 at 21:46
• 41 bytes. but idk if a function call as f(n,*s) is considered valid Jul 12, 2017 at 13:39

# Python 2, 595750 46 bytes

-2 bytes thanks to Anders Kaseorg. -4 bytes thanks to Dennis.

lambda s,n:''.join(i*n**2for i in s)[::n or 1]


Try it online!

# 05AB1E, 10 bytes

S²Ä×J²0‹iR


Try it online!

S          # Split the string into characters
²Ä×       # Repeat each character abs(integer) times
J      # Join into a string
²0‹i  # If the integer is less than 0...
R #   Reverse the string

• TFW you spend 30 minutes trying to come up with something to prove to @Riley that ²0‹i isn't the best route and come up with literally 0 alternatives. Jul 11, 2017 at 21:17
• @MagicOctopusUrn I've used something like ²0‹i before and I always think there has to be something better. Jul 11, 2017 at 21:19
• I think I've tried to find an alternative around 10 times now... wasting a cumulative 3 hours of my life ._. Ä.D)øJ¹0‹iR is the best I can do without copying you, I think yours is optimized. Jul 11, 2017 at 21:20
• If you care, Emigna used è here, though I can't find a way to apply it in this scenario. Would save a maximum of 1 byte, if that. Jul 11, 2017 at 21:53
• SÂÎ›@²Ä×J, using Î to push 0 and input works if you change the order. Saves 1 byte! (Also replaced the if, so it doesn't need to be closed) Jul 12, 2017 at 8:15

# MATL, 9 bytes

y|Y"w0<?P


Inputs are: number, then string.

Strings with newlines are input using char 10 as follows: ['first line' 10 'second line'].

### Explanation

Consider inputs -3 and 'String'.

y      % Implicitly take two inputs. Duplicate from below
% STACK: -3, 'String', -3
|      % Absolute value
% STACK: -3, 'String', 3
Y"     % Run-length decoding
% STACK: -3, 'SSStttrrriiinnnggg'
w      % Swap
% STACK: 'SSStttrrriiinnnggg', -3
0<     % Less than 0?
% STACK: 'SSStttrrriiinnnggg', 1
?      % If so
P    %   Flip
%   STACK: 'gggnnniiirrrtttSSS'
% End (implicit). Display (implicit)


f n|n<0=reverse.f(-n)|1<3=(<*[1..n])


Try it online!

Example usage: f (-3) "abc" yields "cccbbbaaa".

Edit: -5 bytes thanks to xnor!

• There's (<*[1..n]) for ((<$[1..n])=<<). – xnor Jul 11, 2017 at 22:22 • @xnor Thanks! That's good to know. Jul 12, 2017 at 5:58 # V, 29, 23, 18, 17 bytes æ_ñÀuñÓ./&ò ÀäëÍî  Try it online! Hexdump: 00000000: e65f f1c0 75f1 d32e 2f26 f20a c0e4 ebcd ._..u.../&...... 00000010: ee .  Thanks to @nmjcman101 for saving 6 bytes, which encouraged me to save another 5! The original revision was pretty terrible, but now I'm really proud of this answer because it handles negative numbers surprisingly well. (V has next to no numerical support and no support for negative numbers) Explanation: æ_ " Reverse the input ñ ñ " In a macro: À " Run the arg input. If it's positive it'll give a count. If it's negative " running the '-' will cause V to go up a line which will fail since we're " on the first line, which will break out of this macro u " (if arg is positive) Undo the last command (un-reverse the line) Ó./&ò " Put every character on it's own line  At this point, the buffer looks like this: H e l l o w o r l d ! <cursor>  It's important to not the trailing newline, and that the cursor is on it. À " Run arg again. If it's negative, we will move up a line, and then give the " absolute value of the count. If it's positive (or 0) it'll just give the " count directly (staying on the last line) ä " Duplicate... (count times) ë " This column. Íî " Remove all newlines.  • A few bytes for ya Try it online! I always hate the "Negative numbers mean something else!" edge case too. This is a case where your 0 special cases in V came in super handy. Jul 12, 2017 at 2:12 • Sorry about the negative numbers special. However, a lot of answers managed to incorporate that into their main answer. Impressive on this V one though. Jul 12, 2017 at 13:51 • @nmjcman101 Oh wow, that's so obvious, I don't know how I didn't think of it. Thank you! Jul 12, 2017 at 16:47 • @Gryphon Oh I know. The challenge is fine, I just dislike my own language for being so bad at what it's supposed to be good at. :P Jul 12, 2017 at 16:48 ## R, 8378 76 bytes function(s,i)cat('if'(i<0,rev,()(rep(el(strsplit(s,'')),e=abs(i))),sep='')  Anonymous function. Frederic saved 3 bytes, Giuseppe saved 2 4. Explanation:  el(strsplit(s,'')) # split string into list characters rep( ,e=abs(i))) # repeat each character abs(i) times 'if'(i<0,rev, ){...} # if i>0, reverse character list ( # otherwise leave it alone: ( is the identity function cat( ,sep='') # print the result  Tests: > f('Hello World!', 3 ) HHHeeellllllooo WWWooorrrlllddd!!! > f('foo', 12) ffffffffffffoooooooooooooooooooooooo > f('String', -3) gggnnniiirrrtttSSS > f('This is a fun challenge', 0) > f('Hello + World!', 2) HHeelllloo WWoorrlldd!!  • Well done ! You could save a few bytes by writing rep(foo,,,3) or rep(foo,e=3) (same lenght) ;-) Jul 11, 2017 at 22:12 • @Frédéric you beat me to it, I was going to say the same thing! Jul 11, 2017 at 22:13 • yeah, no problem! Basically, I wanted to get rid of the braces, so I needed to get rid of a=. Hence, I used the value of a as an argument to the reverse function if i<0, by having the conditional return the function (which is why I needed the backquotes). But I needed to also apply the identity function for the i>=0 case, so I used ( which is close enough. ( is in fact a function. R is weird. Jul 11, 2017 at 22:39 • btw, the R docs for Paren say that ( is semantically equivalent to the identity function(x)x Jul 12, 2017 at 20:24 • 76 bytes Dec 7, 2017 at 19:10 # 05AB1E, 10 bytes 0‹FR}ʒ¹Ä×?  Try it online! Explanation 0‹F # input_1 < 0 times do: R # reverse input_2 } # end loop ʒ # filter ¹Ä× # repeat current char abs(input_1) times ? # print without newline  # PHP>=7.1, 65 bytes for([,$s,$n]=$argv;$i<strlen($s)*abs($n);)echo$s[$i++/$n-($n<0)];  PHP Sandbox Online • In integer context, $n<0 has the same value as $n<0?:0 but it's 3 bytes shorter :-) Jul 12, 2017 at 12:01 # Brain-Flak (BrainHack), 154 152 bytes ([(({})(<()>))]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>({}<([][()]){{}({<({}<(({}<>)<>)>())>[()]}<{}{}>)([][()])}{}{}<>>){{}{({}<>)<>}(<>)}{}  Try it online! Just here to give DJMcMayhem some competition. ;) ## Explanation Here's a modified version of DJMcMayhem's explanation #Compute the sign and negative absolute value ([(({})<(())>)]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<> #Keep track of the sign ({}< #For each char in the input string: ([][()]) { {} #Push n copies to the alternate stack ({<({}<(({}<>)<>)>())>[()]}<{}{}>) #Endwhile ([][()]) }{}{}<> #Push the sign back on >) #If so... {{} #Reverse the whole stack {({}<>)<>} #And toggle over, ending the loop (<>) } #Pop the counter off {}  # J, 1915 13 bytes (#~|)A.~0-@>]  Try it online! Explanation  0-@>] NB. first or last index depending on sign of right arg A.~ NB. get first or last Anagram of left arg (#~|) NB. copy left arg, absolute-value-of-right-arg times  • (#~|)A.~0-@>] for 13 bytes Jul 12, 2017 at 19:48 • Very nice @miles ! Jul 12, 2017 at 20:20 • No problem. You also don't need to count the parentheses used to invoke the verb. Jul 12, 2017 at 23:20 • Also 13 bytes: #~ ::(|.@#~|) Dec 8, 2017 at 12:26 # Dyalog APL, 15 bytes {⌽⍣(⍵<0)⊢⍺/⍨|⍵}  String as a left argument, number as a right argument. Try it online! How? ⍺/⍨ - repeat the string |⍵ - abs(number) times ⌽⍣ - reverse if (⍵<0) - the number is below 0 • Umm, it'd be nice if the TIO like worked? Jul 11, 2017 at 21:02 • @Gryphon and here goes the byte... Jul 11, 2017 at 21:06 • Yep, I'd just realized that and was typing out my comment to tell you. Jul 11, 2017 at 21:06 # MATLAB, 37 bytes @(s,n)flip(repelem(s,abs(n)),(n<0)+1)  This defines and anonymous function with inputs s: string and n: number. Example runs: >> @(s,n)flip(repelem(s,abs(n)),(n<0)+1) ans = @(s,n)flip(repelem(s,abs(n)),(n<0)+1) >> f = ans; >> f('String', 3) ans = SSStttrrriiinnnggg >> f('String', -3) ans = gggnnniiirrrtttSSS >> f('String', 0) ans = Empty matrix: 1-by-0  • Choosing which dimension to flip along was way better than the mess I wrote 😛 +1. and I always forget repelem exists. Jul 11, 2017 at 22:16 • @StewieGriffin Well, you could incorporate that in your answer too :-) (+1 already). I think there's no repelem in Octave, for now Jul 11, 2017 at 22:19 # Brain-Flak (Haskell), 202 192 bytes (({})<(([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)([][()]){{}({<({}<(({}<>)<>)>[()])>()}<{}{}>)([][()])}{}{}<>>)([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}{({}<>)<>}(<>)}{}  Try it online! This is probably the worst possible language to do it in, but it's done. Thanks to @Wheatwizard for providing the Haskell interpreter, which allows mixed input formats. This would be about 150 bytes longer without it. Explanation: #Keep track of the first input (n) (({})< #Push abs(n) (thanks WheatWizard!) (([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>) #For each char in the input string: ([][()]) { {} #Push n copies to the alternate stack ({<({}<(({}<>)<>)>[()])>()}<{}{}>) #Endwhile ([][()]) }{}{}<> #Push the original n back on >) #Push n >= 0 ([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{} #If so... {{} #Reverse the whole stack {({}<>)<>} #And toggle over, ending the loop (<>) } #Pop the counter off {}  • You could use my 52 byte abs to save 2 bytes, you could also use the 50 byte -abs I gave you and increment instead of decrementing to save 6 bytes. Jul 12, 2017 at 19:57 • Some friendly competition. Jul 12, 2017 at 20:13 # Java (OpenJDK 8), 99988987 85 bytes s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}  Try it online! • -2 bytes thanks to @Xanderhall • -2 bytes thanks to @Nevay • Ideas that don't work (way longer): reverse the string before, use a stream, Jul 12, 2017 at 9:49 • Save 2 bytes with s[(n<0?-l-~i:i)/n] Jul 12, 2017 at 13:19 • @Xanderhall Thanks! I've been looking for that one for so long my eyes bleed. I knew it was possible, I just messed everything up when implementing it. Jul 12, 2017 at 13:20 • @user902383 Yes, it's mandatory. If they were optional, a lot of things would be unreadable. Also, my function is not a "single statement", but a for-loop, which encompass several statements. Jul 13, 2017 at 15:07 • You can save 1 byte by incrementing i in the condition s->n->{for(int l=s.length*(n<0?-n:n),i=0;i++<l;)System.out.print(s[(n<0?i-l:i-1)/n]);}. Another byte can be saved by iterating from -l to 0 instead (s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}). Jul 13, 2017 at 22:58 # Octave, 49 bytes @(s,n){t=repmat(s,abs(n),1)(:)',flip(t)}{2-(n>0)}  Try it online! I will provide an explanation tomorrow. # Ruby, 59 +1 = 60 bytes Uses -n flag. n=eval$_
a=$<.read a.reverse!if n<0 a.chars{|i|$><<i*n.abs}


Try it online!

• eval$_ is shorter than $_.to_i by 1 byte. String#chars can also accept a block the same way String#each_char can. Finally, reverse the input before processing each character so you can print it directly instead (switching your flag to -n). All of this combines to become 55+1=56 bytes. Jul 11, 2017 at 22:14

# Charcoal, 16 bytes

Ｆθ¿‹η0Ｆ±Ｉη←ιＦＩηι


Try it online! Link is to verbose version of code. Explanation:

Ｆθ              For each character in the input string
¿‹η0          If the input number is less than zero
Ｆ±Ｉη      Repeat the negation of the input number times
←ι    Print the character leftwards (i.e. reversed)
ＦＩη       Otherwise repeat the input number times
ι      Print the character


# CJam, 9 bytes

q~__*@e*%


Try it online!

# Japt, 12 bytes

®pVaÃ¬r!+sVg


Try it online!

## Explanation

Implicit input of string U and integer V.

®pVaÃ


Map (®) each letter of U (implicitly) to itself repeated (p) abs(V) (Va) times.

¬r


Turn the string into an array of chars (¬) and reduce (r) that with...

!+sVg


"!+".slice(sign(V)) - this either reduces with +a + b, or with !+b + a.
Thanks @Arnauld for the backwards-reduce idea!

• I feel like £gY*Vg)pVa should lead to a shorter solution but my brain has shut down for the holidays so I can't quite figure it out. You may be able to do something with it, though. Jul 12, 2017 at 7:06

# 05AB1E, 9 bytes

Based off Riley's approach.

SÂÎ›@²Ä×J


Try it online!

### Explanation

SÂÎ›@²Ä×J   Arguments: s, n
S           Push s split into individual characters
Â          Get a (without popping) and push a reversed
Î›        n lower than 0 (true = 1, false = 0)
@       Get value at that index in the stack
²Ä×J   Repeat each character abs(n) times and join
Implicit output


# WendyScript, 46 bytes

<<f=>(s,x){<<n=""#i:s#j:0->x?x>0n+=i:n=i+n/>n}

f("Hello World", -2) // returns ddllrrooWW  oolllleeHH


Try it online!

## Explanation (Ungolfed):

let f => (s, x) {
let n = ""
for i : s
for j : 0->x
if x > 0 n += i
else n = i + n
ret n
}


# C89 bytes

main(int c,char**v){for(;*v[1];v[1]++)for(c=atoi(v[2]+(*v[2]=='-'));c--;)putchar(*v[1]);}


I saw Ben Perlin's version and wondered if you couldn't be shorter still and also have a full program; surely, atoi() and putchar() aren't that expensive in terms of bytes? Seems I was right!

# Pyth, 13 11 bytes

*sm*.aQdz._


Try it!

-2 bytes thanks to @jacoblaw

## explanation

*sm*.aQdz._
m     z     # map onto the input string (lambda var: d)
*.aQd      # repeat the char d as often as the absolute value of the input number
s            # sum the list of strings into a single string
*        ._Q   # Multiply with the sign of the implicit input value: reverse for negative Q


## old approach, 13 bytes

_W<Q0sm*.aQdz


Try it!

• you can save two bytes with this reversal logic Jul 12, 2017 at 23:25

# Python 3, 68 bytes

h=lambda s,n:h(s[::-1],-n)if n<0 else s[0]*n+h(s[1:],n)if s else s*n


Try it online!

• Hello, and welcome to the site! Unfortunately, this answer is invalid right now, since it doesn't support Negative numbers. The challenge says: If the integer is negative, we use its absolute value in the first step, and then reverse the string. Jul 12, 2017 at 20:05
• Thanks for fixing it! BTW, you could take two bytes off by removing the spaces after parenthesis ) Jul 12, 2017 at 20:34
• Edited, thanks for the contribution
– Kavi
Jul 14, 2017 at 16:39
• n<0 else => n<0else Jul 14, 2017 at 16:47

# Excel VBA, 93 89 88 86 85 Bytes

Anonymous VBE immediate window function that takes input as string from cell [A1] and int from cell [B1] and outputs to the VBE immediate window

l=[Len(A1)]:For i=1To l:For j=1To[Abs(B1)]:?Mid([A1],IIf([B1]>0,i,l+1-i),1);:Next j,i


-4 bytes for abandoning [C1] as intermediate variable

-1 byte for adding a as intermediate variable

-2 bytes for replacing a with l, ([Len(A1)])

# C (gcc), 108106103 101 bytes

-2 bytes thanks to ceilingcat

e,p,j,d;f(s,i)char*s;{p=0,e=strlen(s);for(i*=d=i<0?p=e-1,e=-1:1;p^e;p+=d)for(j=i;j--;)putchar(s[p]);}


Try it online!

• @ceilingcat Cheers! Apr 29, 2020 at 22:48

# QBIC, 32 bytes

g=sgn(c)[_l;||[:*g|?_sA,b*g,1|';


## Explanation

            Takes inputs A$('Hello'), and c (-3) from the cmd line g=sgn(c) Save the sign of c -1 [_l;|| FOR each char in A$
[:*g|       FOR the number of repetitions wanted    (ie: -3 * -1)
Note that : reads a number from the cmd line, and c is the first
available variable to save it in after a and b got used as FOR counters.
Also note that a negative value times the sign becomes positive.
?_s         PRINT a substring
A         of A\$
,b*g       startng at char n, where n is the first FOR loop counter times the sign
That means that when c is negative, so is this. A negative starting index
on Substring instructs QBIC to take from the right.
,1|        taking 1 char.
';          This bit injects a literal ; in the output QBasic, to suppress newlines om PRINT