# Stringsplode the String! [duplicate]

The challenge is relatively simple, but will hopefully lead to some wonderfully creative answers. The task is to take a string as an input (via command line, function parameter etc.) and output/return a stringsploded version of it.

A stringsploded version of a string is its first letter followed by its first 2 letters, followed by its first 3 letters,... until you finally output the complete word.

You are guaranteed that the input will consist of printable ASCII characters and that the input will all be on one line (no new line characters).

Here are examples to clarify what stringsplosions are:

Input                 Output
==================================================================
"Code"       ---->   "CCoCodCode"
"name"       ---->   "nnanamname"
"harambe"    ---->   "hhaharharaharamharambharambe"
"sp aces?"   ---->   "sspsp sp asp acsp acesp acessp aces?"
"1234"       ---->   "1121231234"
"ss"         ---->   "sss"


This is code golf so shortest code wins + up votes for interesting uses of your respective language.

Good luck!

• String challenges should usually specify the valid input characters, because it's not clear whether the input may contain a) non-letters, b) unprintable/control characters, c) null bytes, d) extended ASCII characters, e) Unicode characters beyond code point 256, (... f) combining marks, g) surrogates ...), all of which can arbitrarily complicate the challenge in many languages. And since your test cases only cover letters one might assume that that's your intended input range. – Martin Ender Sep 7 '16 at 14:13
• You should add a test case where the first two characters are the same. – mbomb007 Sep 7 '16 at 14:26
• As someone with a stutter, I'm OOfOffOffeOffenOffendOffendeOffended. – Shaun Wild Sep 7 '16 at 15:40
• Alternate title: SStStrStriStrinStringStringsStringspStringsplStringsploStringsplodStringsplode – James Sep 7 '16 at 17:38
• Also related, near duplicate. – ETHproductions Sep 7 '16 at 22:43

# x

• gs2 takes input from STDIN, and pushes it to the stack as a string.
• x is the prefixes built-in, returning a list of all prefixes of the argument, in ascending-length order.
• The resulting list of strings is implicitly printed one-by-one, without a delimiter, when the program terminates.
• Wow Speechless automagic wizardry – Rohan Jhunjhunwala Sep 7 '16 at 23:20

## Jelly, 2 bytes

;\


Acculumate over concatenation gives all prefixes, which Jelly outputs to STDOUT without a delimiter. Try it online!

• Oh, cumulative reduce and reduce never seem to do what I expect. Surely a winner! Test cases – Jonathan Allan Sep 7 '16 at 14:36
• @JonathanAllan Uh oh, Lynn did 1 byte :D – Yytsi Sep 7 '16 at 17:49

## Retina, 4 bytes

.
$  Expects the input to be terminated with a Windows-style \r\n newline (which seems fitting for a .NET-based programming language...). This can be tested on Regex Storm (which uses \r\n newlines). Click the "Context" tab for the result. This is essentially the same as Jordan's Ruby answer: it replaces each character in the input (including the \r but not the \n) with all the characters that came before it. ## Java 7, 81 78 bytes String g(String a){for(int i=a.length();i>0;)a=a.substring(0,--i)+a;return a;}  Straightforward method. Repeatedly prepends the shrinking prefix until it's done. As a bonus, it should work for non-ASCII as well. Sample: Input: ( ͡° ͜ʖ ͡°) Output: (( ( ͡( ͡°( ͡° ( ͡° ͜( ͡° ͜ʖ( ͡° ͜ʖ ( ͡° ͜ʖ ͡( ͡° ͜ʖ ͡°( ͡° ͜ʖ ͡°)  • You've beat me to it. Also, +1 I like the Lenny Face example. – Kevin Cruijssen Sep 7 '16 at 14:29 • Haha, yes. I like to think of it as Lenny sliding into the room Kramer style when he hears something "appropriate". – Geobits Sep 7 '16 at 14:33 # Jelly, 5 4 2 bytes -2 bytes thanks to @Dennis ḣJ  Test it at TryItOnline Or all test cases, also at TryItOnline How? ḣJ - Main link takes one argument, e.g. "Code" J - range(length(input)), e.g. [1,2,3,4] ḣ - head, x[:y] (implicit vectorization), e.g. "CCoCodCode"  • ḣJ works too. – Dennis Sep 7 '16 at 15:13 • @Dennis heh, forgot about J  :) – Jonathan Allan Sep 7 '16 at 15:17 # Brachylog, 11 5 bytes :@[fc  Try it online! ### Explanation :@[f Find all prefixes of the input c Concatenate  # 05AB1E, 3 bytes .pJ  Explanation .p # get list of prefixes of input J # join as string  Try it online! • Damn... I retire – gowrath Sep 7 '16 at 14:08 • That .p idea was a goodun – Jonathan Allan Sep 7 '16 at 14:09 • @JonathanAllan: A prefix command does come in handy now and then yeah :) – Emigna Sep 7 '16 at 14:09 • Well.... Shoot. – user56309 Sep 7 '16 at 16:35 # Ruby, 13 + 1 = 14 bytes +1 byte for -p flag. Expects input on STDIN. Requires Windows-style line endings (\r\n). gsub(/./){$}


See it on eval.in (a few extra bytes since eval.in doesn't support command line flags): https://eval.in/637093

• I think this only works with \r\n newlines. Otherwise, . doesn't have the last character to match (since it doesn't match \n). – Martin Ender Sep 7 '16 at 14:10
• @MartinEnder I was actually just wondering why this works. That explains it. I forgot eval.in uses \r\n. I'll write a version that works with conventional newlines. – Jordan Sep 7 '16 at 14:13
• I think assuming \r\n newlines is fine since that's the default on Windows (and in your online interpreter apparently). But you should mention it in the answer. – Martin Ender Sep 7 '16 at 14:14
• I was going to post a Retina answer but it would now be straight port of yours, so if you want to post it yourself, it's simply . on the first line and $ on the second. – Martin Ender Sep 7 '16 at 14:15 • @MartinEnder If you want to post it I won't take it personally. It's a pretty obvious solution so I don't feel proprietary about it. – Jordan Sep 7 '16 at 14:17 ## Javascript (ES6), 28 26 bytes Recursively appends the shortened strings to the left of the final result: f=s=>s&&f(s.slice(0,-1))+s  ### Examples var f=s=>s&&f(s.slice(0,-1))+s console.log(f("Code")); // --> "CCoCodCode" console.log(f("name")); // --> "nnanamname" console.log(f("harambe")); // --> "hhaharharaharamharambharambe" console.log(f("sp aces?")); // --> "sspsp sp asp acsp acesp acessp aces?" console.log(f("1234")); // --> "1121231234" • Smart use of recursion +1 – Downgoat Sep 7 '16 at 14:50 # MATL, 98 6 bytes 2 bytes saved thanks to @Luis t&+Rf)  Try it Online! Explanation t % Implicitly grab the input and duplicate &+ % Broadcast and create a 2D matrix with all values > 0 R % Grab the upper triangular portion (sets the lower triangular values to 0) f % Get the linear index for each value > 0 ) % Index into the original string (uses modular indexing) % Implicitly display the result  • Cool Solution! (as MATL answers tend to be) – Emigna Sep 7 '16 at 14:11 ## JavaScript (ES6), 25 bytes s=>s.replace(/./g,'$$&')  # Perl, 10 bytes Includes +1 for -p Run with the input on STDIN: splode.pl <<< "Hello"  splode.pl #!/usr/bin/perl -p s/./$/sg


This depends on the input being terminated by a newline. This 11 byte version does not need a final newline:

#!/usr/bin/perl -lp
s/.?/$/g  ## CJam, 8 bytes Here's 4 separate ways to get 8 bytes l_,),\f< l{1$\+}*
l{+_}*co
Ll{+_}/;


Credits to @MartinEnder for the last one. Online interpreter.

• l_,),\f< creates the range [0 .. len(s)+1] then uses f< to slice for each number, producing all prefixes.

• l{1$\+}* is a fold that duplicates the previous prefix and adds a char to it as it goes. • l{+_}*co is a bit weird - l{+_}* is also a fold but it produces the wrong prefixes, skipping the first and doubling the last (e.g. abcd -> ab/abc/abcd/abcd, slashes for clarity). We then use c to turn the last string into just its first character and output it with o, to get the first prefix. • Ll{+_}/; is a for-each loop that also duplicates the previous prefix and adds a char to it as it goes. We have an extra copy of the original string once the loop is over, which we pop with ;. ## Haskell, 34 29 28 26 bytes reverse=<<scanl(flip(:))[]  • I'm just sad I can't use join.inits since neither of those are in the Prelude. – ballesta25 Sep 7 '16 at 17:30 • @ballesta25 I know, FeelsBadMan. – ThreeFx Sep 7 '16 at 18:27 • Hmm, concat.scanl(flip(:))[]$ "Code" -> "CoCdoCedoC". Each part (1st letter, 1st+2nd letter, ...) is in reverse. – nimi Sep 7 '16 at 20:53
• @nimi is right. It needs to be reverse=<<scanl(flip(:))[] – Bergi Sep 8 '16 at 1:10

# C, 49 bytes

i;f(char*n){for(i=0;i++<strlen(n);)write(1,n,i);}


Try on Ideone

• You can golf it down to 41 bytes i;f(char*v){while(*(v+i))write(1,v,++i);} – cleblanc Sep 7 '16 at 15:05

## Jellyfish, 5 bytes

P,\}I


Try it online!

### Explanation

    I  # Read input.
\}   # Get all prefixes.
,     # Flatten.
P      # Print.


# V, 8 bytes

òÄ$xhòíî  Try it online! # C#, 918784 83 bytes void c(string n){var b="";for(int i=0;i<n.Length;)System.Console.Write(b+=n[i++]);}  Ungolfed: void c(string n) { var b = ""; for (int i = 0; i < n.Length ; ) { System.Console.Write(b+=n[i++]); } }  Thank you Kevin Cruijssen. • +1 You can golf a few things, though. string b=""; can be var b=""; and i++ can be removed in the for-loop and added to the usage of i. So in total it becomes: void c(string n){var b="";for(int i=0;i<n.Length;){b+=n[i++];System.Console.Write(b);}} – Kevin Cruijssen Sep 7 '16 at 14:34 • Ah, I can finally comment. Thanks for the suggestions! – Yodle Sep 7 '16 at 14:39 • I've deleted my previous 84 bytes comment, because apparently it's possible to use b+= in the System.out.write.. So b=b+n[i++] can be changed to b+=n[i++] I wasn't sure if += is allowed there, but it is. Guess we both learned some things today. Sorry for making you edit all the time, and welcome to PPCG. :) Also, Tips for golfing in C# might be interesting to read through. – Kevin Cruijssen Sep 7 '16 at 14:44 • Haha yeah. And for sure, I'll be checking a few tips of the languages I know. – Yodle Sep 7 '16 at 14:54 # sed 41 h;:;G;s,.\n,\n,;h;s,\n.*,,;/./b;x;s,\n,,g  # Sesos, 4 bytes 0000000: 8073ec 09 .s..  Try it online! Check Debug to see the generated SBIN code. ### Sesos assembly The binary file above has been generated by assembling the following SASM code.  jmp, rwd 1, jnz fwd 1 jmp, put, fwd 1, jnz jnz  # Python, 34 28 bytes Here's my rough attempt with a recursive solution: f=lambda s:s and f(s[:-1])+s  Ungolfed: def f(s): if s: return f(s[:-1]) + s return ''  Try it here! Thanks to @Dennis for -6 bytes. • I got ninja'd by recursives..... 300th time... – Erik the Outgolfer Sep 7 '16 at 15:59 • f=lambda s:s and f(s[:-1])+s saves 6 bytes. – Dennis Sep 7 '16 at 16:25 • Pretty sure you can remove the f= – Oliver Ni Sep 8 '16 at 1:32 • @OliverNi How would I make the recursive call? – gowrath Sep 8 '16 at 9:05 # CJam, 11 bytes q{(L\+:Lo}h  Explanation: q get input { }h do while (L get 1st character and variable L (initialized with "") \+ swap and concatenate them :Lo store result in L and print it  Try it online # Dyalog APL, 3 bytes ∊,\  ∊ flatten the ,\ cumulative concatenation TryAPL online! # Pyth, 3 bytes s._  Explanation: s (s)um together ._ all prefixes  # R, 60 49 bytes Not going to win any golf, but hopefully no shorter R answer is possible cat(substring(s<-readline(),1,1:nchar(s)),sep="")  paste0(substring(s<-readLines(,1),1,1:nchar(s)),collapse="") Thanks @MickyT • Well there's always cat(substring(s<-readline(),1,1:nchar(s)),sep="") :) – MickyT Sep 7 '16 at 20:00 # Retina, 24 bytes Well, I got destroyed by Martin, but here was my solution. 1m+(.*).$
$1$.1$*¶$0
¶



Try it online

## PowerShell v2+, 43 bytes

param($n)-join(1..$n.length|%{$n[0..--$_]})


Takes input $n, loops from 1 to $n.length, each iteration slicing $n from 0 up to one less than the current number -- done because .length is 1-indexed, while array slicing is 0-indexed. Each iteration places characters on the pipeline, those are encapsulated in parens and -joined together into one string. Output is implicit. PS C:\Tools\Scripts\golfing> .\stringsplode-the-string.ps1 'PPCG' PPPPPCPPCG  Alternatively, using Jordan's Ruby submission as a basis, you can get to the following for 22 bytes $input-replace'.','$'  This feels kinda cheaty, though, since you'd have to explicitly insert a newline into the string that you're piping in, or otherwise do a Get-Content or something out of a file that pulls the newlines with it. Valid, but not really common. PS C:\Tools\Scripts\golfing> 'PPCG ' | .\stringsplode-the-string.ps1$_
PPPPPCPPCG

• If I pipe a string into another program, it gets the \r\n at the end automatically. Looks like PowerShell scripts are treated differently in that regard? – Martin Ender Sep 7 '16 at 14:31
• @MartinEnder Yeah. I'm not sure if it's because piping in PowerShell is handled differently than piping in other shells, or because the items passed between the pipe are literal objects and there's no \r\n at the end of the literal string. Probably a combination. – AdmBorkBork Sep 7 '16 at 14:33

# C 71 67 Bytes

k;f(v){char*m,*n=v;while(*n++)for(k=0,m=v;k<n-v;k++)putchar(*m++);}


# Gema, 16 characters

?=@append{s;?}$s  Sample run: bash-4.3$ echo -n 'sp aces?' | gema '?=@append{s;?}\$s'
sspsp sp asp acsp acesp acessp aces?


# Python 3, 47 bytes

Thanks to @deustice

lambda s:''.join(s[:i]for i in range(len(s)+1))


Ideone it!

• You can take out the 0, just s[:i] should work – deustice Sep 7 '16 at 15:12
• @deustice Oh, of course, thanks! – Beta Decay Sep 7 '16 at 17:03