g | x | w | all
Bytes Lang Time Link
004Vyxal 3250812T123957ZThemooni
019sed250810T103346ZToby Spe
041APLNARS250809T055051ZRosario
019AWK250808T184656Zxrs
031Alice230816T024125ZJulian
004Thunno 2230816T061557ZThe Thon
026ARBLE230815T222624ZATaco
113Fortran201202T031400Zroblogic
023Factor210928T005109Zchunes
015K ngn/k201201T223351Zcoltim
082C gcc210315T085305Zl4m2
040Java 8170901T091635ZKevin Cr
072Nim210123T224535ZAdam
037Python 3210123T213143Zqwatry
005Husk201202T033434ZRazetime
008GolfScript200109T143903Zuser8505
056Wren200108T141218Zuser8505
015Zsh190826T184010ZGammaFun
023k4190826T170056Zscrawl
004Japt Q170831T163314ZShaggy
069Tcl170922T001818Zsergiol
042Jq 1.5170922T020129Zjq170727
040Powershell170922T101208Zwhatever
017Perl 5170922T020913ZXcali
044Octave170921T235124ZLuis Men
nan170831T191307ZTriggern
00905AB1E170831T165234ZMagic Oc
010Pyth150521T001323ZTyilo
049JavaScript ES6150520T154538Zedc65
025Haskell150520T165454Znimi
014Bash150522T222733Zmichael5
037Python2150520T165220Zuser1220
028KDBQ150522T160107ZWooiKent
215ObjectiveC150522T150700ZFennelou
023Ruby150521T231741ZSheharya
007CJam150520T152011ZOptimize
068Cobra150521T062859ZΟurous
032Bash150520T210550ZDeltik
075Mathematica150520T210537ZLegionMa
045R150520T184551ZAlex A.
042golfua150520T164616ZKyle Kan
018///150520T164952Zmanatwor
022Perl150520T153205Zr3mainer

Vyxal 3, 4 bytes

⌈ꜝ„q

Vyxal It Online!

⌈ꜝ„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"/>

sed, 19 bytes

s/ *\([" ]\) */\1/g

Try it online!

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"

AWK, 19 bytes

{for(;$++i;)$i=$i}1

Attempt This Online!

Alice, 31 bytes

/ot!h';$ !Q'w!/
@Mq!"~K'.% >]]\

Try it online!

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Ṙ

Try it online!

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.

Try it online!

Fortran, 113 bytes

Try it Online!

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.

Previously: 127 bytes, 147 bytes

Factor, 23 bytes

[ [ 32 = ] " "compact ]

Try it online!

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

" "/(~#:')_" "\

Try it online!

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);}

Try it online!

Java 8, 40 bytes

s->'"'+s.replaceAll(" +"," ").trim()+'"'

Explanation:

Try it here.

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" ",'"'

Try it online!

Ignoring the IO restrictions as many answers do, 58 bytes:

import strutils
echo stdin.readAll.splitWhitespace.join" "

Try it online!

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.

Try it online!

Husk, 5 bytes

sJ' w

Try it online!

Fully ascii!

Explanation

sJ' w
    w split into words
 J'   join with spaces
s     add quotes

GolfScript, 8 bytes

' '%' '*

Try it online!

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(" ")}

Try it online!

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}\"

Try it online!

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

Japt -Q, 10 4 bytes

¸f ¸

Try it

Tcl, 69 bytes

puts [string map {{ "} \" {" } \"} [regsub -all \ + [gets stdin] \ ]]

Try it online!

Tcl, 79 bytes

puts \"[string trim [regsub -all \ + [string range [gets stdin] 1 end-1] \ ]]\"

Try it online!

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

Try it online

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.

Perl 5, 17 bytes

16 bytes of code + 1 for -p

s/ *("| ) */$1/g

Try it online!

Octave, 44 bytes

@(x)[34 strjoin(regexp(x,'\S+','match')) 34]

Try it online!

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ðý'".ø

Try it online!


#         | 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:

Test cases screenshot

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:

Test Cases:

enter image description here

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

Try it online here

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.