| Bytes | Lang | Time | Link |
|---|---|---|---|
| 004 | Vyxal 3 | 250812T123957Z | Themooni |
| 019 | sed | 250810T103346Z | Toby Spe |
| 041 | APLNARS | 250809T055051Z | Rosario |
| 019 | AWK | 250808T184656Z | xrs |
| 031 | Alice | 230816T024125Z | Julian |
| 004 | Thunno 2 | 230816T061557Z | The Thon |
| 026 | ARBLE | 230815T222624Z | ATaco |
| 113 | Fortran | 201202T031400Z | roblogic |
| 023 | Factor | 210928T005109Z | chunes |
| 015 | K ngn/k | 201201T223351Z | coltim |
| 082 | C gcc | 210315T085305Z | l4m2 |
| 040 | Java 8 | 170901T091635Z | Kevin Cr |
| 072 | Nim | 210123T224535Z | Adam |
| 037 | Python 3 | 210123T213143Z | qwatry |
| 005 | Husk | 201202T033434Z | Razetime |
| 008 | GolfScript | 200109T143903Z | user8505 |
| 056 | Wren | 200108T141218Z | user8505 |
| 015 | Zsh | 190826T184010Z | GammaFun |
| 023 | k4 | 190826T170056Z | scrawl |
| 004 | Japt Q | 170831T163314Z | Shaggy |
| 069 | Tcl | 170922T001818Z | sergiol |
| 042 | Jq 1.5 | 170922T020129Z | jq170727 |
| 040 | Powershell | 170922T101208Z | whatever |
| 017 | Perl 5 | 170922T020913Z | Xcali |
| 044 | Octave | 170921T235124Z | Luis Men |
| nan | 170831T191307Z | Triggern | |
| 009 | 05AB1E | 170831T165234Z | Magic Oc |
| 010 | Pyth | 150521T001323Z | Tyilo |
| 049 | JavaScript ES6 | 150520T154538Z | edc65 |
| 025 | Haskell | 150520T165454Z | nimi |
| 014 | Bash | 150522T222733Z | michael5 |
| 037 | Python2 | 150520T165220Z | user1220 |
| 028 | KDBQ | 150522T160107Z | WooiKent |
| 215 | ObjectiveC | 150522T150700Z | Fennelou |
| 023 | Ruby | 150521T231741Z | Sheharya |
| 007 | CJam | 150520T152011Z | Optimize |
| 068 | Cobra | 150521T062859Z | Οurous |
| 032 | Bash | 150520T210550Z | Deltik |
| 075 | Mathematica | 150520T210537Z | LegionMa |
| 045 | R | 150520T184551Z | Alex A. |
| 042 | golfua | 150520T164616Z | Kyle Kan |
| 018 | /// | 150520T164952Z | manatwor |
| 022 | Perl | 150520T153205Z | r3mainer |
Vyxal 3, 4 bytes
⌈ꜝ„q
⌈ꜝ„q
⌈ # split on spaces
ꜝ # discard empty strings
„ # join on spaces
q # quotify string
💎
Created with the help of Luminespire.
<script type="vyxal3">
⌈ꜝ„q
</script>
<script>
args=[["this is a string "],[" blah blah blah "],["abcdefg"],["12 34 ~5 6 (7, 8) - 9 - "],[" "]]
</script>
<script src="https://themoonisacheese.github.io/snippeterpreter/snippet.js" type="module"/>
APL(NARS), 41 chars
{k←(w≠' ')⊂w←,⍵⋄z←¯1↓↑,/k,¨' '⋄'"',z,'"'}
test:
f←{k←(w≠' ')⊂w←,⍵⋄z←¯1↓↑,/k,¨' '⋄'"',z,'"'}
f ''
""
f ' '
""
f ' '
""
f 'this is a string '
"this is a string"
f 'thisisstring'
"thisisstring"
f 'a '
"a"
f 'a'
"a"
Alice, 31 bytes
/ot!h';$ !Q'w!/
@Mq!"~K'.% >]]\
Mt!h~;' %Qw]!]' !.$K'"!qo@ Flattened, without flow characters
M Read an argument, push it on the stack
t!h~; Remove the leading and trailing quote, write one of them on the tape
' Adds a space on the stack
% Pop the space, pop the argument, split the argument by space and push all of them words on the stack
Q Reverse the stack
w .$K While the stack is not empty
] Go to the end of the tape
!] Pop a word from the stack, write to the tape, go to the end of the tape
' ! Add a space on the stack
'"! Write a quote on the tape, overwriting the last space
q Concatenate the content of the tape, word and spaces, push the result on the stack
o Pop, output the concatenated result
@ Bye
Thunno 2, 4 bytes
OðjṘ
Explanation
OðjṘ # Implicit input
# Implicit eval to
# remove the quotes
O # Split on spaces
ðj # Join on spaces
Ṙ # Repr (surround
# by quotes)
# Implicit output
ARBLE, 26 bytes
join(explode(s,"%S+")," ")
explode groups by non-spaces, and then join re-concatenates them.
Fortran, 113 bytes
character(99)S;read(*,'(A)')S;S='"'//trim(adjustl(S))//'"'
do i=1,99;if(S(i:i+1)>' ')call fput(S(i:i));enddo;end
Per wikibooks, "It should be remembered that Fortran is designed for scientific computing and is probably not a good choice for writing a new word processor."
Fortran doesn't have a regex concept either. This just makes string challenges more interesting!
In this solution, we trim the string S, then iterate over it. Print each character unless it's a space followed by another space.
Factor, 23 bytes
[ [ 32 = ] " "compact ]
Factor has a combinator called compact that does this. From the documentation:
Generate a new sequence where all runs of elements for which the predicate returns true are replaced by a single instance of elt. Runs at the beginning or end of the sequence for which the predicate returns true are removed.
K (ngn/k), 21 18 16 15 bytes
" "/(~#:')_" "\
" "\split (implicit) input on spaces(~#:')_drop empty strings" "/join remaining items with spaces
C (gcc), 82 bytes
char*s=&s+9;main(t){for(gets(s);*s;s++)*s>32|(s[1]>32&&s[2]&&t)&&putchar(*s,--t);}
Java 8, 40 bytes
s->'"'+s.replaceAll(" +"," ").trim()+'"'
Explanation:
s-> // Method with String as parameter and return-type
'"' // Return a leading quote
+s.replaceAll(" +", // + Replace all occurrences of multiple spaces in the input
" ") // with a single space
.trim() // and remove all leading and trailing spaces
+'"' // + a trailing quote
Nim, 72 bytes
import strutils
echo'"',stdin.readAll[1..^2].splitWhitespace.join" ",'"'
Ignoring the IO restrictions as many answers do, 58 bytes:
import strutils
echo stdin.readAll.splitWhitespace.join" "
Python 3, 37 bytes
print("%r"%' '.join(input().split()))
Based of user12205's python2 answer. I've replaced the %s with a %r so that single quotes are printed around the string automatically.
Husk, 5 bytes
sJ' w
Fully ascii!
Explanation
sJ' w
w split into words
J' join with spaces
s add quotes
GolfScript, 8 bytes
' '%' '*
Explanation
The logic is quite simple:
' '% # Split on spaces, remove empty results
' '* # Join on spaces
Wren, 56 bytes
Wait. The replace only does it once? Now I have to use the split-join combo.
Fn.new{|x|x.trim().split(" ").where{|i|i!=""}.join(" ")}
Explanation
Fn.new{|x| } // New anonymous function with the operand x
x.trim() // Trim out whitespace from both sides of the string
.split(" ") // Split the string into space-separated chunks
.where{|i|i!=""} // Keep all of those that aren't the null string (due to two consecutive spaces)
.join(" ") // Join the replaced list together
Zsh, 15 bytes
<<<\"${(Qz)1}\"
Input string contains embedded quotes. Remove the Q for 14 bytes if the input string does not contain embedded quotes, as is done in some of the other answers here.
Parameter expansion flags: Q dequotes, then z splits into words as the shell does. The words are then implicitly joined by spaces.
k4, 23 bytes
" "/:x@&~~#:'x:" "\:0:0
0:0 / read from stdin
x:" "\: / split string on spaces and assign to x
~~#:' / boolean true where string len>0, bool false otherwise
x@& / x at indices where true
" "/: / join with spaces
Tcl, 69 bytes
puts [string map {{ "} \" {" } \"} [regsub -all \ + [gets stdin] \ ]]
Tcl, 79 bytes
puts \"[string trim [regsub -all \ + [string range [gets stdin] 1 end-1] \ ]]\"
Jq 1.5, 42 bytes
split(" ")|map(select(length>0))|join(" ")
Sample Run
$ jq -M 'split(" ")|map(select(length>0))|join(" ")' < data
"this is a string"
"blah blah blah"
"abcdefg"
""
"12 34 ~5 6 (7, 8) - 9 -"
$ echo -n 'split(" ")|map(select(length>0))|join(" ")' | wc -c
42
Powershell, 40 bytes
"`"$(($args-Replace' +'," ").trim())`""
Pretty straight forward and not very impressive.
Explanation
Take input parameter via (predfined) args-variable, replace all multiple spaces with one, trim leading and trailing spaces using trim()-method, add quotes. Powershell will print strings to console as default behavior.
Python2, 28 Bytes
lambda s:" ".join(s.split())
Explanation
lambda s
Anonymous function which takes as input s.
s.split()
Returns a list of the words (which are separated by arbitrary strings of whitespace characters) of the string s.
" ".join(...)
Joins list back into a string, with each word separated by a space (" ").
05AB1E, 9 bytes
#õKðý'".ø
# | Split on spaces.
õK | Remove empty Strings.
ðý | Join with spaces.
'".ø | Surround with quotes.
Pyth, 17 15 11 10 bytes
(thanks to Ypnypn and FryAmTheEggman)
pjd-cQdkNN
Could probably be golfed more.
If the output can use ' instead of " then I only need 8 bytes:
`jd-cQdk
JavaScript (ES6), 49 52 58
Edit 6 bytes shorter, thanks to @Optimizer
Edit 2 -3, thanks to @nderscore
Input/output via popup. Using template string to cut 1 byte in string concatenation.
Run snippet to test in Firefox.
alert(`"${prompt().match(/[^ "]+/g).join(" ")}"`)
Haskell, 31 25 bytes
fmap(unwords.words)readLn
words splits the string into a list of strings with spaces as delimiters and unwords joins the list of strings with a single spaces in-between. The quotes " are stripped of and put back by Haskell's read and show (implicitly via the REPL) functions on strings.
Outputting by the function itself is three bytes longer, i.e. 28 bytes:
print.unwords.words=<<readLn
Edit: @Mauris pointed to the readLn function, which saved some bytes.
Bash ,14 bytes
read f;echo $f # assume f="this is a string "
Python2, 37
Reduced by 1 byte thanks to @ygramul.
print'"%s"'%' '.join(input().split())
Original version:
print'"'+' '.join(input().split())+'"'
Test cases:

KDB(Q), 28 bytes
" "sv except[;enlist""]" "vs
Explanation
" "vs / cut string by space
except[;enlist""] / clear empty strings
" "sv / join back with space
Test
q)" "sv except[;enlist""]" "vs"12 34 ~5 6 (7, 8) - 9 - "
"12 34 ~5 6 (7, 8) - 9 -"
Objective-C 215
-(NSString*)q:(NSString*)s{NSArray*a=[s componentsSeparatedByString:@" "];NSMutableString*m=[NSMutableString new];for(NSString*w in a){if(w.length){[m appendFormat:@"%@ ",w];}}return[m substringToIndex:m.length-1];}
Uncompressed version:
-(NSString*)q:(NSString*)s{
NSArray *a=[s componentsSeparatedByString:@" "];
NSMutableString *m=[NSMutableString new];
for (NSString *w in a) {
if (w.length) {
[m appendFormat:@"%@ ",w];
}
}
return[m substringToIndex:m.length-1];
}
Ruby, 31 29 25 23 Bytes
p$*[0].strip.squeeze' '
Code Explanation:
poutputs string within double quotes toSTDOUT(There's more to it though...)$*is an array ofSTDINinputs,$*[0]takes the first onestripremoves starting and ending spacessqueeze ' 'replaces >1 space characters with a single space
Test Cases:

CJam, 7 bytes
q~S%S*p
Code Explanation
CJam has reserved all capital letters as inbuilt variables. So S has a value of a space here.
q~ e# Read the input (using q) and evaluate (~) to get the string
S% e# Split on running lengths (%) of space
S* e# Join (*) the splitted parts by single space
p e# Print the stringified form (p) of the string.
This removes the trailing and leading spaces as well
Cobra - 68
As an anonymous function:
do
print'"[(for s in Console.readLine.split where''<s).join(' ')]"'
Bash, 36 32 bytes
As a function, a program, or just in a pipe:
xargs|xargs|xargs -i echo '"{}"'
Explanation
The first xargs strips the quotation marks.
The second xargs trims the left side and replaces multiple adjacent spaces in the middle of the string with one space by taking each "word" and separating each with a space.
The xargs -i echo '"{}"' trims the right side and rewraps the resulting string in double quotes.
Mathematica, 75 bytes
a=" ";b=a...;Print[InputString[]~StringReplace~{b~~"\""~~b->"\"",a..->a}]
R, 45 bytes
cat('"',gsub(" +"," ",readline()),'"',sep="")
The readline() function reads from STDIN, automatically stripping any leading and trailing whitespace. Excess space between words is removed using gsub(). Finally, double quotes are prepended and appended and the result is printed to STDOUT.
Examples:
> cat('"',gsub(" +"," ",readline()),'"',sep="")
This is a string
"This is a string"
> cat('"',gsub(" +"," ",readline()),'"',sep="")
12 34 ~5 6 (7, 8) - 9 -
"12 34 ~5 6 (7, 8) - 9 -"
golfua, 42 bytes
L=I.r():g('%s*\"%s*','"'):g('%s+',' ')w(L)
Simple pattern matching replacement: find any double quotes (\") surrounded by 0 or more spaces (%s*) & return the single quote, then replace all 1 or more spaces (%s+) with a single space.
A Lua equivalent would be
Line = io.read()
NoSpaceQuotes = Line:gsub('%s*\"%s*', '"')
NoExtraSpaces = NoSpaceQuotes:gsub('%s+', ' ')
print(NoExtraSpaces)
///: 18 characters
/ / //" /"// "/"/
Sample run:
(Using faubiguy's interpreter from his Perl answer for Interpret /// (pronounced 'slashes').)
bash-4.3$ ( echo -n '/ / //" /"// "/"/'; echo '" foo * bar "'; ) | slashes.pl
"foo * bar"
Perl, 22
(20 bytes of code, plus 2 command line switches)
s/ +/ /g;s/" | "/"/g
Needs to be run with the -np switch so that $_ is automatically filled via stdin and printed to stdout. I'm going to assume this adds 2 to the byte count.