# Repeat every other character in string starting with second character

Requirements:

• Take a single word as input with only lowercase alphabetical characters (a-z)
• Output a string where every other character is repeated, with the first repeated character being the second character in the string

Example:

Input: abcde

Output: abbcdde

Winning Criteria:
Standard code golf. Shortest number of bytes in program wins.

Clarification:
For languages with 1-based indexing the output must still match the above, aabccdee is not an acceptable solution.

• May we start from 1 as the first character, for the benefit of languages with 1-based indexing? Feb 1 '20 at 0:08
• Sure, i just called the first character 0th so my title "repeat odd index characters" makes sense. As long as you the output is repeating "Every other" character starting from the second character I the string (which I call index 1) then it's acceptable Feb 1 '20 at 0:10
• I suggest you use standard I/O rules instead of requesting to use stdin (and never saying to use stdout, by the way). Or is there some reason to avoid it? Feb 1 '20 at 20:23
• Also, python answer is already a function that actually uses argument for input and return for output, so I'm assuming that you actually allow default I/O ways and are not restricting to stdin. Feb 1 '20 at 20:31
• @Neyt "Every other" is an English phrase that could mean all but one exception but in this case it does not. It is similar to "alternating", for example "every other day" means "either all even days and no odd days or all odd days and no even days". I don't think there is really any logic to it. If you are still confused the ESL stack exchange is probably the place to ask about this further. Feb 3 '20 at 16:52

# GolfScript, 16 bytes

GolfScript doesn't have item count so you will need to do it yourself.

1:&;{]&):&2%)*}%


Try it online!

## Explanation

# Implicitly pushed input
1:&;             # set count to 1
{         }% # foreach item of input
]&):&       #     add count by one
2%)*   #     repeat item by cnt % 2 + 1


# JavaScript (ES6), 28 bytes

Uses the same regex as @DigitalTrauma.

s=>s.replace(/.(.)/g,"$&$1")


Try it online!

# JavaScript (ES6), 32 bytes

A recursive version.

f=([a,b,...c])=>b?a+b+b+f(c):[a]


Try it online!

# Lua, 34 bytes

print(((...):gsub('.(.)','%0%1')))


Try it online!

Takes input as an argument, prints result to stdout. Every two characters are replaced with themselves and second one appended.

# Perl 6, 14 bytes

{S:g[.<(.]x=2}


Try it online!

Regex that matches every other character and substitutes it with itself string multiplied by 2.

# PHP, 37 bytes

while($c=$argn[$i++])echo$c,$c[$i%2];


Try it online!

# naz, 44 bytes

2a2x1v1x1f1r3x1v2e1o1r3x1v2e2o1f0x1x2f0a0x1f


Works for any input string terminated with the control character STX (U+0002).

Explanation (with 0x commands removed)

2a2x1v                     # Set variable 1 equal to 2
1x1f1r3x1v2e               # Function 1
# Read a byte of input
1o             # Otherwise, output it once
1r3x1v2e     # Read another byte of input
2o   # Otherwise, output it twice
1f # Jump back to the start of function 1
1x2f0a                     # Function 2
# Add 0 to the register
1f                         # Call function 1


# Whitespace, 66 bytes

[S S S T    N
_Push_1][N
S S N
_Create_Label_LOOP][S S S T N
_Push_1][T  S S S _Add][S S S T S N
_Push_2][T  S T T   _Modulo][S N
S _Dupe][S N
S _Dupe][S N
S _Dupe][S N
S _Dupe][T  N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][T  N
S S _Print_as_character][N
T   S N
_If_0_Jump_to_Label_LOOP][T T   T   _Retrieve_input][T  N
S S _Print_as_character][N
S N
N
_Jump_to_label_LOOP]


Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer n = 1
Start LOOP:
n = (n+1) modulo-2
Integer c = STDIN as character
Print c as character to STDOUT
If(n == 0):
Go to the next iteration of LOOP
Print c as character to STDOUT
Go to the next iteration of LOOP

• I really would like to master loops and conditional in WhiteSpace. Haven't quite been able to get one working yet. Feb 6 '20 at 17:27
• @ouflak I can certainly recommend to use the vii5ard compiler when you're developing in Whitespace. It allows you to debug through the code, and see the values on the stack and heap in the memory-tab. You can even set breakpoints. Also, maybe the more in-depth explanation in this Whitespace interpreter challenge of mine might clarify a thing or two in comparison to the tutorial linked in the title. Feb 6 '20 at 17:53
• @ouflak For a loop you basically mark a location with a Label, and you Jump to that label later on. Here for example an infinite loop printing a 1 every iteration: NSSN SSSTN TNST NSNN (create label (empty); push 1; pop and print as integer; jump to label (empty)). For an if-statement you'd have to make the value either 0 or negative, and use the conditional jumps. You usually do have to duplicate the value if you still need it later on however, since the conditional labels will pop the value. Feb 6 '20 at 17:55
• @ouflak If you have any questions in particular, or want me to turn a provided pseudo-code into a Whitespace program with explanation, feel free to contact me again. PS: Unfortunately you can't save / link from the vii5ard compiler, which is why I have TIO links in my answers. I never create the programs in TIO though, always in vii5ard. Feb 6 '20 at 17:56

# Perl 5-p, 13 bytes

s/.\K./$&$&/g


Try it online!

# JavaScript (V8), 76685648 44 bytes

Thanks to Malivil for 12 bytes !

s=>s.split.map((v,i)=>i%2==1?v+v:v).join


Try it online!

• Welcome to the site. Your submission seems to take input by inserting it into the code. The challenge requires that input be taken from standard in that would be the input field on TIO. Feb 3 '20 at 16:39
• @PostRockGarfHunter Sorry about that, i've added an edited version. Feb 3 '20 at 16:40
• You can save a few more bytes by changing v.repeat(2) to v+v Feb 3 '20 at 16:48
• Actually you can save more by using the newer syntax for those empty string functions, like this Feb 3 '20 at 16:54
• 38 bytes: s=>[...s].map((v,i)=>i%2?v+v:v).join Feb 5 '20 at 9:38

# brainfuck, 18 bytes

>,[>,]<[<]>[.>..>]


Requires 0-termination for EOF. Prints two trailing null bytes for odd-length strings.

Try it online!

– Jo King
Feb 3 '20 at 22:14
• @JoKing Still figuring that out :). Feb 3 '20 at 22:16

# PowerShell, 26 bytes

$args-replace'.(.)','$0$1'  Try it online! # Burlesque, 11 bytes 2co{J[-j}\m  Try it online! 2co # Split into chunks of 2 {"ab" "cd" "e"} { J # Duplicate pair of chars [- # Take the tail (returns empty for length 1 strings) j # Swap to correct order for concat }\m # For each pair, and then concatenate  # Burlesque, 8 bytes 2co)+.\[  Try it online! Works for even length strings only 2co # Same as above )+. # For each group append the last char again \[ # Concatenate  # APL (Dyalog), 12 11 bytes -1 byte thanks to Bubbler ∊⊢⍴⍨¨1 2⍴⍨≢  Try it online! A train that takes a string and returns a string (or any list technically). ### Explanation:  ⍴⍨ ⍝ Reshape ¨ ⍝ Each of ⊢ ⍝ The input 1 2 ⍝ To the array 1 2 ⍴⍨ ⍝ Reshaped to ≢ ⍝ The length of the input ∊ ⍝ And flatten the result  # Forth (gforth), 46 bytes : f 0 do dup dup 1 type i 2 mod type 1+ loop ;  Try it online! ### Code Explanation : f \ start a new word definition 0 do \ loop from 0 to string-len - 1 dup dup \ duplicate the current character address twice 1 type \ output the current letter i 2 mod type \ if odd, output again, if even do nothing (0 type = output nothing) 1+ \ increment current character address loop \ end loop ; \ end word definition  # .+?, 11 bytes (.(.)) \1\2  The first answer in my new language. It's a simple language based around python regex substitution # Explanation (.(.)) Replace each pair of characters with \1\2 matching group 1 (both characters) followed by matching group 2 (the second character)  Try it online! (The second command line argument is input) • Nice approach! Isn't \0/$0 possible in Python or your language? I.e. .(.) and \0\1? Feb 20 '20 at 16:37
• Sadly not, python's regexes are pretty limited compared to most other flavours Feb 20 '20 at 16:42

# Ruby, 25 bytes

->s{s.scan(/(.(.?))/)*''}


Try it online!

Same byte count as the other answer, different approach.

# C (gcc), 66 $$\\cdots\$$ 59 57 bytes

Saved a 3 bytes thanks to ceilingcat!!!
Saved a byte thanks to S.S. Anne!!!

i;f(c){for(i=0;~(c=getchar());printf(&c))c*=i++%2?257:1;}


Try it online!

• Save another by swapping c and i and initializing i at its definition. Feb 3 '20 at 17:29
• @S.S.Anne Nice one - thanks! :-) Feb 3 '20 at 18:06
• @ceilingcat Nice one - thanks! :-) Jul 25 '20 at 14:02

# Rockstar, 95 bytes

listen to S
cut S
X's0
Y's0
while S-X
let S at X be*1+Y
let Y be not Y
let X be+1

join S
say S


Try it here (Code will need to be pasted in)

# GNU AWK, 36 bytes

BEGIN{RS=".|";ORS=e}$0=NR%2?RT:RT RT  BEGIN{RS=".|";ORS=e} This reads one character at a time, which can be retrieved by the RT variable.$0=NR%2?RT:RT RT      If NR=1 (mod 2), i.e., True, assigns "RT" to the output.
Otherwise, assigns "RT RT", which is RT concatenated to itself.
This conditional simply doubles the even occurrences.


Try it online!

## @, 13 bytes

¤+ōČōōČ


## Explanation

  ōČ    Take a character and print it.
ōōČ Take a character and print it twice.
¤+      Repeat this forever.


# Funky, 34 bytes

s=>fori=0i<#s i++write(s[i]*1+i%2)


A pretty simple solution to the problem.

Try it online!

# Charcoal, 8 bytes

⭆Ｓ×ι⊕﹪κ²


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

 Ｓ          Input string
⭆           Map over characters and join
²    Literal 2
κ     Current index
﹪      Modulo
⊕       Incremented
ι        Current character
×         Repeated
Implicitly print


# APL+WIN, 13 bytes

Prompts for string:

((⍴s)⍴⍳2)/s←⎕


Try it online! Courtesy of Dyalog Classic.

# SimpleTemplate, 44 bytes

This was easy, but also fun!

{@eachargv.0}{@echo_}{@if__ is mod2}{@echo_}


Loops through all the characters, and checks if the index of the character (__) is not a multiple of 2 (odd). If it isn't a multiple of 2, outputs it again.

Ungolfed:

Just in case you are curious.

{@each argv.0 as char key key}
{@echo char}
{@if key is not multiple of 2}
{@echo char}
{@/}
{@/}

• The as char is optional, using the variable _ by default, to hold the array item/character from the string.
• The key key is optional, using the variable __ by default, to hold the index.
• All the {@/} ae optional and safe to remove.

You can try it on http://sandbox.onlinephpfunctions.com/code/5fc880374f58b72c4dc3ee2c573349e7a218aed8 You can check and try both golfed and ungolfed versions.

# C (gcc), 49 48 bytes

-1 thanks to ceilingcat

M;f(c){++M%3?c=getchar():0;M=~c&&f(putchar(c));}


Try it online!

i=1;f(c){for(;-~(c=getchar());i^=1)printf("%c%1$c"+i*2,c);}  Using original input rules. Try it online! # C (gcc), 54 bytes i=1;f(char*s){for(;*s;i^=1)printf("%c%1$c"+i*2,*s++);}


Using acceptable input.

Try it online!

• 53 bytes Jul 24 '20 at 4:53

Assuming your string are all alphabetically sorted, you can use:

# Python 3, 42 bytes:

lambda x:''.join(sorted(x[1::2]*2+x[::2]))


Try it online!

# PowerShell, 102 bytes

function b($i){$c=0;$o;$i.ToCharArray().ForEach{if($c%2-eq1){$o+="$_$_"}else{$o+="$_"}$c++;};write$o}


Try it online!

## Unix TMG, 59 bytes

p:parse((c={1}))parse((c={1 1}))\p;c:smark any(!<<>>)scopy;


# CJam, 12 bytes

q2/{_La+1=}%


Try it online!

## Explanation

q2/{_La+1=}%
q2/           Read the input and split it into groups of 2 characters.
{      }%  For each group:
_           Copy it.
La+        Append an empty string.
1=      Get its second element.
Join the results.