| Bytes | Lang | Time | Link |
|---|---|---|---|
| 086 | C clang | 250813T140611Z | jdt |
| 020 | Pip | 250811T183009Z | DLosc |
| 014 | Vyxal 3 | 250811T212245Z | pacman25 |
| 107 | APLNARS | 250810T125917Z | Rosario |
| 040 | Dyalog APL | 250810T225013Z | Aaron |
| 058 | Perl 6 | 151027T212147Z | Brad Gil |
| 034 | Perl | 151021T103201Z | svsd |
| nan | Perl 5 | 151020T113807Z | LukStorm |
| 070 | MUMPS | 151020T224913Z | senshin |
| 032 | Pyth | 151020T134328Z | RK. |
| 023 | Pyth | 151020T174752Z | FryAmThe |
| 020 | CJam | 151020T033253Z | Dennis |
| 097 | Haskell | 151020T110500Z | lynn |
| 043 | Ruby | 151020T100708Z | lynn |
| 047 | Gema | 151020T102117Z | manatwor |
| 038 | Retina | 151020T092032Z | Martin E |
| 055 | Ruby | 151020T090713Z | Martin E |
| 186 | C++11 | 151020T085807Z | Zereges |
| 065 | Python 3 | 151020T030522Z | user4594 |
| 049 | JavaScript ES6 | 151020T050550Z | Downgoat |
| 033 | Pyth | 151020T034958Z | Moose |
| 034 | CJam | 151020T034335Z | GamrCorp |
| 066 | Julia | 151020T033750Z | Alex A. |
C (clang), 86 bytes
p[];i;f(char*s){sscanf(s,"%d:%[^:]:%[^:]",&i,p,s);s[i]&&printf("%.*s%s%s",i,s,p,s+i);}
Pip, 22 20 bytes
{c~XX*a.:b.$'}MUg^':
Takes the input as a command-line argument. If the index is too large, the output is empty.
Explanation
{c~XX*a.:b.$'}MUg^':
g List of command-line args (in this case, a list of
one element)
^': Split on colons
{ }MU Map this function to each sublist, assigning its elements
to the local variables a, b, and c:
a First element (the index number)
XX* Regex matching that many of any character
~ Find first regex match in
c Third element (the word string)
.: To that match, concatenate
b Second element (the pattern string)
. Concatenated with
$' The part of c after the match
The map returns a list containing a single value
Concatenate list together and autoprint (implicit)
If the index is too large, the regex fails to match, which causes the function's return value to be nil. Nil outputs nothing, which means that printing a list containing nil outputs only a trailing newline.
APL(NARS), 107 chars
I←{(a b)←⍺⋄(a≠⌊a)∨(a≤0)∨a>k←1+≢⍵:⍬⋄w←(((a-1)⍴1),0,(k-a)⍴1)\⍵⋄w[a]←b⋄w}
f←{(n r s)←⍵⊂⍨⍵≠':'⋄c←⍎n⋄∊c(⊂r)I s}
//71+36=107
1-indexed.
The function I is the function insert in the position a number ⍺[1],
the element ⍺[2], in the list ⍵.
If the function I fail for wrong a it will return zilde ⍬.
The function of exercise f use I, ⊂ for add a single element (even if an array),
and ∊ for enlist.
Test:
f '0:this:that'
┌0─┐
│ 0│
└~─┘
f '1:this:that'
┌8────────┐
│ thisthat│
└─────────┘
f '2:this:that'
┌8────────┐
│ tthishat│
└─────────┘
f '3:this:that'
┌8────────┐
│ ththisat│
└─────────┘
f '4:this:that'
┌8────────┐
│ thathist│
└─────────┘
f '5:this:that'
┌8────────┐
│ thatthis│
└─────────┘
f '6:this:that'
┌0─┐
│ 0│
└~─┘
f '1.3:this:that'
┌0─┐
│ 0│
└~─┘
2 '123' I '345'
RANK ERROR
2 '123' I '345'
∧
2 (⊂'123') I '345'
┌4───────────┐
│ ┌3───┐ │
│3 │ 123│ 4 5│
│¯ └────┘ ¯ ¯2
└∊───────────┘
Dyalog APL, 40 chars
{p i w←⍵⊆⍨⍵≠':'⋄(p←⍎p)>≢w:⍬⋄(p↑w),i,p↓w}
A little imperative for my liking....
{p i w←⍵⊆⍨⍵≠':'⋄(p←⍎p)>≢w:⍬⋄(p↑w),i,p↓w}
⍵⊆⍨⍵≠':' # Break in the input on the delimiter ':'
p i w← # And store into (p)osition, (i)nsert, and (w)ord
(p←⍎p) # Execute the position var to convert from string to actual number
>≢w:⍬ # If that is bigger than the length of the word, output nothing (as opposed to crashing)
(p↑w) # Take the first p many letters from word
,i # concat with the word to insert
,p↓w # concat with the remainder of word
💎
Created with the help of Luminespire.
Perl 6, 58 bytes
$_=[split ':',@*ARGS];substr-rw(.[2],.[0],0)=.[1];.[2].say
Perl, 34 bytes
(includes 1 switch)
perl -pe '$x="."x$_;s/.*:(.*):($x)|.*/$2$1/'
Prints an empty line on error.
Perl 5, 41 Bytes (40 + 1)
Outputs 0 when a replacement couldn't be made.
($n,$s,$_)=split/:/;$_=0if!s/.{$n}/$&$s/
Test
$ echo "6:Online :Hello World!" |perl -p -e '($n,$s,$_)=split/:/;$_=0if!s/.{$n}/$&$s/'
$ Hello Online World!
MUMPS, 70 bytes
a(s) s w=$P(s,":",3) q:s>$L(w) w $E(w,1,s)_$P(s,":",2)_$E(w,s+1,9**9)
There is no output if an invalid index is provided.
This code is basically ANSI-compliant; the only issue is that I've saved a byte by taking advantage of the fact that the maximum length of a string on the two major surviving MUMPS platforms is less than 99 bytes: InterSystems Caché caps strings at 32 KiB, and GT.M caps strings at 1 MiB. Nonetheless, in principle, some jerk could write an implementation that allows strings over ~369 MiB, in which case there would be valid inputs for which this code fails.
We can save 3 additional bytes, bringing us down to 67, if we use non-ANSI Caché ObjectScript-specific extensions to $EXTRACT:
a(s) s w=$P(s,":",3) q:s>$L(w) w $E(w,1,s)_$P(s,":",2)_$E(w,s+1,*)
Pyth, 32 bytes
Beats the other Pyth answer! Still needs a lot of golfing though. Took the naïve approach.
?gleJcz":"KvhJ++:eJ0KhtJ:eJKleJ"
Pyth, 23
*sX0ceJcz\:KvhJhtJgleJK
Unfortunately (in this scenario anyway), Pyth doesn't error on chopping a string by too large a value. Otherwise the check would go from 6 bytes to 2.
I'm unsure if this is the most optimal approach, but this chops the word after the number of characters from the input. Then it does a += on the first element of the list and returns the sum. It multiplies the resulting string by a boolean representing if the value was out of range.
Also note that this does not work if the input is 0. The OP said we could assume the number is positive, so I believe this is ok.
CJam, 20 bytes
q':/~La+@~/(@@_{];}|
Try it online in the CJam interpreter.
How it works
q':/ e# Read all input and split it at colons.
~ e# Dump index, pattern and word on the stack.
La+ e# Append the array [""] to the word.
e# This increases the word's length by 1 (to deal with the
e# highest index possible index) without affecting output.
@~ e# Rotate the index on top and evaluate it.
/ e# Split the word into chunks of that length.
( e# Shift out the first chunk.
@@ e# Rotate pattern and remaining chunks on top.
_ e# Copy the array of remaining chunks.
e# This array will be empty if the index was too high.
{];}| e# If the array if falsy, clear the stack.
Haskell, 97 bytes
a=fmap tail.span(/=':')
m!(n,e)|m>length e=""|0<1=take m e++n++drop m e
f l|(o,r)<-a l=read o!a r
Defines f, a function that takes a string like "2:x:ABC" and returns "ABxC".
Ruby, 43 bytes
37 bytes of code:
G,O,L=$F
$_=(L[G.to_i,0]=O;L)rescue p
and 6 bytes of flags:
$ ruby -apF: code.rb < input
^^^^^^
Gema: 47 characters
*\:*\:*=@subst{<U$1>\*=\$1@quote{$2}\*\;\*=;$3}
Sample run:
bash-4.3$ gema '*\:*\:*=@subst{<U$1>\*=\$1@quote{$2}\*\;\*=;$3}' <<< '3:!*!:Hello'
Hel!*!lo
bash-4.3$ gema '*\:*\:*=@subst{<U$1>\*=\$1@quote{$2}\*\;\*=;$3}' <<< '13:!*!:Hello'
(If you want an explicit error message, just insert it after the last = sign.)
Retina, 38 bytes
(()1)*:(.+):((?<-2>.)*)(?!\2)|^.+
$4$3
Run the code from a single file with the -s flag. This takes input in unary, e.g.
111:A2C:Hello World!
yields
HelA2Clo World!
If the index is too large, an empty line will be printed.
Ruby, 55 bytes
a,b,c=gets.split ?:;(c[a,0]=b;p c)if c.size>=(a=a.to_i)
It's been a while since I've golfed in Ruby... this feels a bit suboptimal.
C++11, 186 bytes
Golfed
#include<iostream>
#include<regex>
int main(){std::string p,w;int i,j;std::getline(std::cin>>i,p);j=p.find(58,1);w=p.substr(j+1);if(i<=w.length())std::cout<<w.insert(i,p.substr(1,j-1));}
Ungolfed
#include <iostream>
#include <regex>
int main()
{
std::string p, w;
int i, j;
std::getline(std::cin >> i, p);
j = p.find(':', 1);
w = p.substr(j + 1);
if (i <= w.length())
std::cout << w.insert(i, p.substr(1, j - 1));
}
Looking for: Improvements and someone who can do Shakespear, so that I am not last again :)
Python 3, 65 bytes
a,b,c=input().split(':')
a=int(a)
if c[a-1:]:print(c[:a]+b+c[a:])
Does nothing if the index is past the end of the string. Try it online.
JavaScript ES6, 49 bytes
s=>([a,b,c]=s.split`:`,c.slice(0,a)+b+c.slice(a))
Very straightforward. Slices the string and inserts the new substring in the middle
Pyth, 33
=Ycw\:JvhYp?>leYJjk[<eYJ@Y1>eYJ)Z
Prints 0 if the index is past the end of the string
CJam, 34 bytes
Terribly ungolfed, but its my first CJam golf ever! Thanks to sp3000 for helping me with this on The Nineteenth Byte chat!
l':/~_,W$i>{W$i/(:+-2$+-3$+:+p}&];
EDIT: oops, I was in the process of posting this and I didn't see Dennis' CJam post. If the answers do end up using the same process, just count mine as a non-competitive answer. Sorry for the confusion.
Julia, 66 bytes
s->(x=split(s,":");i=parse(Int,x[1]);x[3][1:i]*x[2]*x[3][i+1:end])
This creates an unnamed function that accepts a string and returns a string. It errors if the index is out of bounds.
Ungolfed:
function f(s::AbstractString)
# Split the input on the colon
x = split(s, ":")
# Convert the first element of x to an integer
i = parse(Int, x[1])
# Join the pieces
return x[3][1:i] * x[2] * x[3][i+1:end]
end