Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Full width text is text that has a space after every character, including the last one. For instance, the first sentence of this question becomes:

F u l l   w i d t h   t e x t   i s   t e x t   t h a t   h a s   a   s p a c e   a f t e r   e v e r y   c h a r a c t e r ,   i n c l u d i n g   t h e   l a s t   o n e . 

Write a program that takes a line in text from standard input and outputs it as full-width text to standard out.

Leaderboard

var QUESTION_ID=75979,OVERRIDE_USER=52353;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

share|improve this question
1  
So, if I understand, we can't take input as a function parameter (or output as a return value)? – Nathan Merrill Mar 22 at 17:50
3  
Usually you should allow functions too, or you exclude a lot of languages (e.g. JavaScript). – wizzwizz4 Mar 22 at 18:00
2  
We have a few defaults for I/O that are based on community consensus. While you are entitled to override them, insisting on STDIN/STDOUT for I/O invalidates a bunch of answers (which assumed that the defaults apply) and make the task downright impossible in other languages (they don't have standard streams). – Dennis Mar 22 at 21:22
24  
That is not what fullwidth text is. – BlueRaja - Danny Pflughoeft Mar 22 at 21:53
3  
@BlueRaja-DannyPflughoeft is right. Full Width text is about underlying character encoding ( 2 bytes encoded ) required by some language ( i.e. ideograms ). In Unicode the notion of half and full size is called Unicode block – Ludovic Frérot Mar 23 at 9:27

74 Answers 74

Jelly, 5 3 2 bytes

Thanks to Dennis for saving 2 bytes. Also thanks to FryAmTheEggman for saving 1 byte. Code:

p⁶

Explanation:

p⁶   # Cartesian product with the input and the space character.

Uses the Jelly encoding.

Try it online!

share|improve this answer
1  
⁶ takes up three bytes in UTF-8. – Jess Smith Mar 22 at 18:02
9  
@JessSmith Jelly uses its own code page: github.com/DennisMitchell/jelly/blob/master/docs/code-page.md – quartata Mar 22 at 18:02
1  
@AandN Put it in the answer, not a comment. – mbomb007 Mar 22 at 20:08
2  
@mbomb007 It's right in the header. – Adnan Mar 22 at 20:09
4  
@AandN No, you should say in your answer that it has its own code page. Especially since it's a newer language, so people don't know yet. – mbomb007 Mar 22 at 20:10

Python 3.5, 18 bytes

print(*input(),'')

This works because print's default separator is single space.

share|improve this answer
2  
print(*input(),end=' ') would be portable, but it's not very golfy... – Dennis Mar 22 at 20:35
4  
MFW the first use of my PEP I see in the wild is on Code Golf. – Veedrac Mar 23 at 8:15

Hexagony, 21 13 12 10 bytes

Code:

Saved a lot of bytes thanks to FryAmTheEggman. Code:

P,<0/*;@.>

Or in a more readable form:

  P , <
 0 / * ;
@ . > . .
 . . . .
  . . .

Try it online!

Explanation:

The Hexagony program starts at the top-left corner, immediately setting the memory edge to the ASCII value of P, which is 80. After that, we can see that the following path is taken:

enter image description here

We can see that the path taken is: P,<;.P/0....;*/>. After the P, we take a byte of user input. If this is empty, the following branch (<) would direct us to the North East. If the input is non-empty, the branch directs us to the South East. After that, we output the user input using ;. We set the memory edge back to P, which is 80. The zero followed by the mirror is then concatenated to our number, resulting into 800. This is then outputted using the ; command, but first it is taken modulo 256, resulting into 32, which is the space character. After that, we reset the memory edge using the * command and return to loop over the rest of the user input. When we're done with the user input, the path is directed to the North East:

enter image description here

This basically goes to the @ command, which terminates the program.

Using Timwi's amazing HexagonyColorer for making the diagrams.

share|improve this answer
    
Uh, I was golfing while you edited. Oops. 10: P,<0/*;@.> – FryAmTheEggman Mar 22 at 19:33
    
@FryAmTheEggman Hahaha, let's make a new explanation then :p. – Adnan Mar 22 at 19:39
    
P,<<>0;@>* is also 10, but unfortunately I don't think it helps in shaving off another byte. – Martin Ender Mar 23 at 6:54
    
@MartinBüttner Oh, that's a shame. I doubt if it's possible to shave off another byte, but it seems unlikely. – Adnan Mar 24 at 16:03

Haskell, 11 bytes

((:" ")=<<)

Usage example: ((:" ")=<<) "Code Golf" -> "C o d e G o l f ".

Map each character c to a two element list [c, space] and concatenate everything into a single list.

share|improve this answer
    
Interesting that Haskell and Jelly are kind of doing the same thing here, since the list monad acts similarly to a Cartesian product. – ballesta25 Mar 24 at 5:43

Retina, 5

.
$& 

Note the space at the end of the second line.

$& is equivalent to $0. Thanks to @mbomb007 for this link.

Try it online.

share|improve this answer
    
@FryAmTheEggman I prefer to use $0. It's the same thing, but more common. – mbomb007 Mar 22 at 19:42
    
Here's a useful reference to go along with Retina's wiki: msdn.microsoft.com/en-us/library/… – mbomb007 Mar 22 at 19:45

JavaScript, 20 Bytes

Simple, I just wish that Array.join added the space to the end so I could save 3 bytes.

s=>[...s,``].join` `
share|improve this answer
5  
[...s,``].join` ` perhaps? – Neil Mar 22 at 18:39
    
That works, thanks. – Generic User Mar 23 at 1:11

><>, 13 10 bytes

3 bytes saved thanks to @Sp3000

i:0(?;o 'o

Try it here. Click the link, then Submit, then type some input and press Give, and finally run the program with Start or Run without animation.

Explanation

i       read a character
:       duplicate
0(      is it less than 0?
?;      if so: end program. Else:
o       output read character
 '      push all chars until matching (same) quote. Top character is a space
o       output that character, which is a space. Go back to the beginning
share|improve this answer
    
i:0(?;o 'o for 10 – Sp3000 Mar 23 at 1:51
    
In fact, io 'o works too, erroring out. – Sp3000 Mar 23 at 1:52
    
@Sp3000 Thanks! I'll go for the no-error version (maybe you want to submit yours?). I forgot you can input chars directly. How does the unmatched quote work? Does it always pick the preceding char? – Luis Mendo Mar 23 at 1:56
1  
' just wraps around, pushing chars until it finds another ' to close it. In this case the opening and closing 's are the same char and most of the source code is pushed, but the top char would just be space since it was pushed last. – Sp3000 Mar 23 at 1:57
    
@Sp3000 Got it. So that's also cyclical. Thanks a lot for the suggestion and explanation! – Luis Mendo Mar 23 at 1:58

C, 56 Bytes (as program argument), 46 Bytes (from stdin)

main(int a,char**b){while(*b[1])printf("%c ",*b[1]++);}

Plain old C answer. Once compiled, the program needs to be called with a string as it's first parameter, a string with spaces needs to be enclosed in quotes. For the example in the start post:

./prog "Full width text is text that has a space after every character, including the last one."

Which will output

F u l l   w i d t h   t e x t   i s   t e x t   t h a t   h a s   a   s p a c e   a f t e r   e v e r y   c h a r a c t e r ,   i n c l u d i n g   t h e   l a s t   o n e .

Solution that reads directly from stdin.

main(c){while(c=~getchar())printf("%c ",~c);}

One byte less thanks to @FryAmTheEggman

share|improve this answer
    
The requirements are a little murky, but I believe you have to read the input from stdin rather than taking it as an argument. Also, here is a page with some useful tips for further golfing in C: codegolf.stackexchange.com/q/2203/13877 – Josh Mar 22 at 19:59
    
@Josh Does it count as a parameter to main? Because otherwise, the Java answer will be just as wrong, and not so sure about the Haskell one either. – SBI Mar 22 at 20:04
    
Either is fine we like our I/O to be friendly :) But I do believe using getchar() is shorter. Also you don't need the include for most C compilers. – FryAmTheEggman Mar 22 at 20:06
    
@FryAmTheEggman I left the include in to be completely compliant, I can only test with gcc. As long as gcc-only is fine, yeah, shaving the include is alright. – SBI Mar 22 at 20:10
    
Generally, if it works with Ideone it's ok :) – FryAmTheEggman Mar 22 at 20:12

WhoScript 38 bytes

1v;pr;e;#0 1;-;i;t=;ti;o;tl;" ";d;>;pf

Works best when the string is given at the command line, but it can be done one character at a time in real time as well.

Ungolfed:

time_vortex
  psychic_paper read
  duplicate
  # 0 1
  -
  integer
  TARDIS =
  TARDIS if
      opening
  TARDIS landing
  # 20
paradox
pop
psychic_paper flush
share|improve this answer

Labyrinth, 10 bytes

<.23.%):,>

This terminates with an error, but the error messages goes to STDERR.

Try it online!

Explanation

This is one of the rare cases where a completely linear program is feasible. The loop is achieved via the source code modification commands < and >, which works because after each iteration we know that the stack is empty again.

< cyclically shifts the entire line one cell to the left, so we end up with:

.23.%):,><

This takes the instruction pointer (IP) with it so the IP is now at the right end of the code and has to move left. Next, the > does the opposite modification so it shifts the source code back to

<.23.%):,>

Now we execute a single iteration (from right to left), before everything starts over:

,    Read a character code from STDIN, or -1 at EOF.
:)   Duplicate and increment.
%    Modulo. At EOF this will attempt a division by zero and terminate. Otherwise, we
     have n % (n+1) = n, so we're left with the input character again.
.    Print it back to STDOUT.
32   Turn the top of the stack into a 32.
.    Print it as well (a space).
share|improve this answer

Java, 132 (System.in) or 99 (Program argument) bytes

Can you feel the overhead tonight?

class F{public static void main(String[]a){System.out.print(new java.util.Scanner(System.in).nextLine().replaceAll("(.)", "$0 "));}}
class W{public static void main(String[]a){for(char c:a[0].toCharArray())System.out.print(c+" ");}}

shooqie figured out a 6 byte shorter way to do this but I won't steal their approach. I've used it with the STDIN and lambda versions, however.

28 characters for a lambda but that doesn't meet the program requirement.

s->s.replaceAll("(.)","$0 ")
share|improve this answer
    
The question specified that the input must be from STDIN. – EMBLEM Mar 22 at 20:17
    
I could add one for you, if that's ok. – Blue Mar 22 at 21:26
    
I've added a STDIN version now (and used the clever regexplace shooqie figured out). – CAD97 Mar 23 at 1:47

Gema, 5 bytes

?=?\ 

Sample run:

bash-4.3$ gema '?=?\ ' <<< 'Full width text.'
F u l l   w i d t h   t e x t . 
share|improve this answer
    
I haven't seen this language before. Link to the interpreter? – quartata Mar 26 at 4:57
    
Sorry. Added hyperlink to the post title. Quite old, but sadly, Google can efficiently help finding it only if you know that the name comes from “general purpose macro processor”. – manatwork Mar 26 at 13:52

Seriously, 7 bytes

' ;,@j+

Try it online!

Man, that required ending space added 3 additional bytes. Without it, ,' j would work for 4.

Explanation:

' ;,@j+
' ;      push two copies of a single space
   ,@    push input, swap
     j+  join on spaces, append a space
share|improve this answer

05AB1E, 4 bytes

Sð«J

Try it online.

Explanation

Sð«J

S     split string into a list
 ð«   append a space to each element
   J  join
share|improve this answer

CJam, 5 4 bytes

1 byte fewer thanks to @FryAmTheEggman

lSf+

Try it online!

Explanation

l     e# read line
Sf+   e# map "concatenation" (+) with a space (S) as extra parameter
      e# implicitly display characters in the stack
share|improve this answer

GolfScript, 6 bytes

' ':n*

Try it online!

share|improve this answer

Awk, 7 bytes

(4 characters code + 3 characters command line option.)

NF++

Sample run:

bash-4.3$ awk -F '' 'NF++' <<< 'Full width text.'
F u l l   w i d t h   t e x t . 

(There is some disagreement on what should be included in the command line option count. I included what is actually passed to the awk interpreter: “-”, “F” and a separator between “F” and the empty string parameter. See below what I mean.)

bash-4.3$ od -tax1 /proc/`pidof awk`/cmdline 
0000000   a   w   k nul   -   F nul nul   N   F   +   + nul
         61  77  6b  00  2d  46  00  00  4e  46  2b  2b  00
                         ╰────────╯
share|improve this answer

brainfuck, 24 bytes

Simple example using the shortest known 32 for the space character(s).

>-[-[-<]>>+<]>->,[.<.>,]

Try it online

share|improve this answer

Befunge-93, 12 bytes

~:1+!#@_, ",

Tested using this online interpreter.

~                           Read char
 :1+!                       Push (char == -1)
     #@_                    Halt if so, i.e. on EOF
        ,                   Output char
          "~:0`!#@_, "      Push the chars between the quotes, one by one
                      ,     Output the top char, i.e. space
share|improve this answer
    
Wow, sleek usage of " and wrap-around – daniero Mar 23 at 18:21

Cubix, 10 bytes

Cubix is a 2 dimensional language developed by @ETHproductions where the commands are wrapped onto a cube. Try it online

@.?wi^\oSo

This maps onto a cube with edge length 2

    @ .
    ? w
i ^ \ o S o . .
. . . . . . . .
    . .
    . .

Starts with a input i. The flow is redirected north ^ to the top face. ? If the value is negative turn left to finish @, zero carries on into shift right w or positive turn right then reflect left \. Output character with a trailing space oSo.

share|improve this answer

Labyrinth, 11 bytes

32@
 :,
 ..

This is an 11-byte answer which terminates without an error – see @MartinBüttner's answer for a 10-byte answer which terminates with an error. Try it online!

Starting from the top-left, we have the following setup step:

32        Turn a zero at the bottom of the stack into 32 (space)

Then we turn right at the 2, entering the following tight loop:

:          Duplicate top of stack (space)
,          Read char from STDIN
.          Output char
.          Output space

This loop repeats until , reads EOF, which pushes -1 to the top of the stack. The -1 makes us turn left into the @, terminating the program.


Here are two additional error-free 11-byte solutions, by Martin:

Extra version A

  3
.:2
.,@

This version is the same as the above, but rotated 90 degrees. We still start on the 3, since this is the first valid instruction in reading order.

Extra version B

^,.
@:.
2
3

This version is effectively the same as the previous two, but uses an initial ^ to rotate the first column upon running the program, such that the board becomes:

@,.
2:.
3
^

After this, the code is the same as the original, except rotated 90 degrees in the other direction.

share|improve this answer

Sed, 8 bytes

's/$*/ /g'

Can be run from bash as

$ sed 's/$*/ /g' <<< "Full Width Text."

Outputs

 F u l l   w i d t h   t e x t .
share|improve this answer
    
Nice answer, but i think you mean '/g/ in the test case not '/f'. +1 though. – Eᴀsᴛᴇʀʟʏ Iʀᴋ Mar 24 at 2:47
    
Thank you, 'f' is right next to 'g' on the dvorak keyboard – Ben Perlin Mar 24 at 3:37
    
My understanding is that a leading space is not permitted. – Neil Mar 24 at 10:55

MATL, 7 bytes

tnZ"v1e

Try it online!

Explanation

t    % implicitly take input string and duplicate it
n    % number of elements
Z"   % string with that many spaces
v    % concatenate vertically (2xN array, where N is input length)
1e   % reshape into 1 row. Implicitly display
share|improve this answer

Minkolang 0.15 - 9 bytes

od?.O" "O

Try it here!

Explanation

o            Take character from input
 d           Duplicate top of stack
  ?.         Pop top of stack and jump over the . if truthy, stop otherwise
    O        Output input char
     " "O    Output a space

Minkolang's codebox is toroidal, hence there is no need to put an explicit loop in it.

share|improve this answer

Pyke, 5 bytes

dm+s_

Explanation:

d     -    load ' ' onto the stack
 m+   -   map(add, eval_input_or_not(), " ")
   s  -  "".join(^)
    _ - ^[::-1]

At the moment Pyke has a bug where if map is given a string, it reverses it :(

share|improve this answer

sed, 8 bytes

s/./& /g

When running this from the shell you should quote it of course e.g.

echo Full Width Text | sed 's/./& /g' | od -c
share|improve this answer

Java, 92

class T{public static void main(String[]A){System.out.print(A[0].replaceAll("(.)","$0 "));}}
share|improve this answer

SMBF, 9 bytes

Note the trailing space. Uses the space in the code rather than creating a 32 in a cell.

,[.<.>,] 

The tryitonline.net interpreter appears to have a bug and loop indefinitely with this, so it only works in my Python interpreter. Changing the SMBF source code (currently on line 171) inside the Python code is required.

share|improve this answer

Vitsy, 10 bytes

zl\[O' 'O]

z          Grab all string input.
 l\[     ] Do the stuff in the brackets length of the stack times.
    O   O  Output as character.
     ' '   Push literal space.

Try it online!

share|improve this answer

Go, 154 120 bytes

package main
import(
."fmt"
."os"
."strings")
func main(){s:=Join(Args[1:], " ")
for _,c:=range s{Print(string(c)," ")}}

Saved a few bytes with command line args.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.