19
\$\begingroup\$

You are given a string. Output the string with one space per words.

Challenge

Input will be a string (not null or empty), surrounded with quotes(") sent via the stdin. Remove leading and trailing spaces from it. Also, if there are more than one space between two words (or symbols or whatever), trim it to just one space. Output the modified string with the quotes.

Rules

  • The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to ~(tilde) (character codes 0x20 to 0x7E, inclusive) except ",i.e, the string will not contain quotes(") and other characters outside the range specified above. See ASCII table for reference.
  • You must take input from the stdin( or closest alternative ).
  • The output must contain quotes(").
  • You can write a full program, or a function which takes input (from stdin), and outputs the final string

Test Cases

"this is a string " --> "this is a string"
" blah blah blah " --> "blah blah blah"
"abcdefg" --> "abcdefg"
" " --> ""
"12 34 ~5 6 (7, 8) - 9 - " --> "12 34 ~5 6 (7, 8) - 9 -" 

Scoring

This is code golf, so the shortest submission (in bytes) wins.

asked May 20, 2015 at 15:16
\$\endgroup\$
9
  • 1
    \$\begingroup\$ You say must take input from stdin, and later you say ...or a function which takes input, and outputs the final string. Does this mean the function must take input from stdin as well? \$\endgroup\$ Commented May 20, 2015 at 15:35
  • \$\begingroup\$ @blutorange , Yes. Edited to clarify it. \$\endgroup\$ Commented May 20, 2015 at 15:36
  • 2
    \$\begingroup\$ " "aa" " --> ""aa"" (are quotes valid inside the input string?) \$\endgroup\$ Commented May 20, 2015 at 15:36
  • \$\begingroup\$ @edc65 , Good point. The answer to that is no. Edited to clarify it. \$\endgroup\$ Commented May 20, 2015 at 15:51
  • 1
    \$\begingroup\$ Some answers are processing string including the double quotes: " this ", others process a once double quoted string which reaches the code with the double quotes already stripped off: ` this `. This way the answers and the languages'/authors' efficiencies are not really comparable. @CoolGuy, could you firmly clarify the requirement on this? \$\endgroup\$ Commented May 22, 2015 at 10:49

43 Answers 43

1
2
12
\$\begingroup\$

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

answered May 20, 2015 at 15:20
\$\endgroup\$
10
\$\begingroup\$

///: 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"
answered May 20, 2015 at 16:49
\$\endgroup\$
2
  • 13
    \$\begingroup\$ Haven't I seen this program somewhere before? \$\endgroup\$ Commented May 20, 2015 at 17:48
  • \$\begingroup\$ Technically you're not taking input though. ;) There's this language but reading input is still quite a pain I think. \$\endgroup\$ Commented May 20, 2015 at 22:00
5
\$\begingroup\$

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.

answered May 20, 2015 at 15:32
\$\endgroup\$
3
  • 1
    \$\begingroup\$ same solution: sed -E 's/ +/ /g;s/" | "/"/g' \$\endgroup\$ Commented May 20, 2015 at 16:01
  • 3
    \$\begingroup\$ The same thing is 12 bytes in Retina. :) \$\endgroup\$ Commented May 20, 2015 at 16:24
  • \$\begingroup\$ -p implies -n, so you only have to take a +1 penalty here (assuming you don't just switch to a different language, like the other commenters suggest). \$\endgroup\$ Commented Dec 18, 2016 at 8:44
5
\$\begingroup\$

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.

answered May 20, 2015 at 21:05
\$\endgroup\$
4
  • 2
    \$\begingroup\$ Wow! That is tricky. Unfortunately not handles test case 4, but still impressing. \$\endgroup\$ Commented May 21, 2015 at 7:46
  • \$\begingroup\$ Yeah, this code meets the fourth test case and is shorter. \$\endgroup\$ Commented May 21, 2015 at 10:27
  • \$\begingroup\$ Can you do something like this? x=xargs;$x|$x|$x -i echo '"{}"' \$\endgroup\$ Commented Sep 1, 2017 at 5:09
  • \$\begingroup\$ @Cyoce: You could indeed do that to save one byte at the cost of losing pipe functionality. Still not as short as this solution and still doesn't satisfy the fourth test case. \$\endgroup\$ Commented Sep 1, 2017 at 7:44
5
\$\begingroup\$

Ruby, (削除) 31 (削除ここまで) (削除) 29 (削除ここまで) (削除) 25 (削除ここまで) 23 Bytes

p$*[0].strip.squeeze' '

Code Explanation:

  • p outputs string within double quotes to STDOUT (There's more to it though...)
  • $* is an array of STDIN inputs, $*[0] takes the first one
  • strip removes starting and ending spaces
  • squeeze ' ' replaces>1 space characters with a single space

Test Cases:

enter image description here

answered May 21, 2015 at 23:17
\$\endgroup\$
11
  • 1
    \$\begingroup\$ You can replace ARGV with $* saving two bytes. gsub /\s+/, ' ' can be replaced with squeeze ' ' for another 4 bytes \$\endgroup\$ Commented May 22, 2015 at 9:57
  • \$\begingroup\$ @DickieBoy, thank you for $*, I didn't know that. But we can't replace gsub /\s+/, ' ' with squeeze because they are not the same. \$\endgroup\$ Commented May 22, 2015 at 10:09
  • \$\begingroup\$ What do you mean by "are not the same"? The outputs are the same. \$\endgroup\$ Commented May 22, 2015 at 10:16
  • 1
    \$\begingroup\$ squeeze ' ' will only squeeze spaces. "yellow moon".squeeze "l" => "yelow moon" \$\endgroup\$ Commented May 22, 2015 at 10:24
  • 2
    \$\begingroup\$ Personally I am. And some of other answerers too. But as I see, neither you are alone with your interpretation... A clarification from the question owner would be welcome. By the way, both the space between p and its parameter and squeeze and its parameter are unnecessary. \$\endgroup\$ Commented May 22, 2015 at 10:42
4
\$\begingroup\$

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
answered May 21, 2015 at 0:13
\$\endgroup\$
6
  • \$\begingroup\$ You can use N instead of \" \$\endgroup\$ Commented May 21, 2015 at 0:23
  • \$\begingroup\$ Welcome to Pyth, Tylio. The second program could be shorterned by the use of d. \$\endgroup\$ Commented May 21, 2015 at 7:29
  • \$\begingroup\$ @isaacg haven't I already used d for everything it can be used for? \$\endgroup\$ Commented May 22, 2015 at 23:38
  • \$\begingroup\$ @Tyilo I think you made an edit at about the same time I commented. It's all good now. \$\endgroup\$ Commented May 22, 2015 at 23:48
  • \$\begingroup\$ You can use p to save a few bytes on string concatenation instead of many +es. pjd-cQdkNN \$\endgroup\$ Commented May 23, 2015 at 3:38
3
\$\begingroup\$

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.

answered May 20, 2015 at 16:54
\$\endgroup\$
3
  • \$\begingroup\$ I'm getting Parse error: naked expression at top level when I tested both the codes here \$\endgroup\$ Commented May 21, 2015 at 8:45
  • \$\begingroup\$ @CoolGuy: rextester.com expects whole programs, not functions, so try main=interact$show.unwords.words.read. There's an online REPL at the frontage of haskell.org (requires cookies enabled) where you can try fmap(unwords.words.read)getLine. \$\endgroup\$ Commented May 21, 2015 at 14:19
  • 1
    \$\begingroup\$ fmap(unwords.words)readLn and print.unwords.words=<<readLn are a bit shorter. \$\endgroup\$ Commented May 23, 2015 at 1:38
3
\$\begingroup\$

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

answered May 20, 2015 at 15:45
\$\endgroup\$
9
  • \$\begingroup\$ alert(`"${eval(prompt()).match(/\S+/g).join(" ")}"`) - 52 \$\endgroup\$ Commented May 20, 2015 at 15:50
  • \$\begingroup\$ @Optimizer thx. Note, that just works after the last clarification about the quotes: eval('" " "') would crash. \$\endgroup\$ Commented May 20, 2015 at 15:55
  • \$\begingroup\$ When I tested the fourth test case (using chrome), no popup (which shows the result) is seen. Why? \$\endgroup\$ Commented May 21, 2015 at 8:42
  • \$\begingroup\$ @CoolGuy maybe because Chrome does not run ES6? I never test ES6 with Chrome. Anyway I tried it now in my Chrome (42.0.2311.152) and works for me. \$\endgroup\$ Commented May 21, 2015 at 10:49
  • \$\begingroup\$ -3: alert(`"${prompt().match(/[^ "]+/g).join(" ")}"`) \$\endgroup\$ Commented May 23, 2015 at 15:54
2
\$\begingroup\$

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 -"
answered May 20, 2015 at 18:45
\$\endgroup\$
3
  • \$\begingroup\$ Not sure if it complies totally with the rules, but the cat may not be totally required, just the gsub. The output from that is [1] "This is a string" \$\endgroup\$ Commented May 20, 2015 at 19:26
  • \$\begingroup\$ @MickyT: Thanks for the suggestion. My interpretation based on the OP's comment (first on the post) was that it had to be printed to stdout. I'll ask for clarification. \$\endgroup\$ Commented May 20, 2015 at 19:28
  • \$\begingroup\$ Ahhh ... didn't see that comment or requirement \$\endgroup\$ Commented May 20, 2015 at 19:30
2
\$\begingroup\$

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

answered May 20, 2015 at 16:52
\$\endgroup\$
2
  • \$\begingroup\$ I really wanted to use print" ".join(raw_input().split()), but it would have a trailing space inside the last quotation mark if there were spaces after the last word... \$\endgroup\$ Commented May 20, 2015 at 19:24
  • \$\begingroup\$ You can shave off an extra byte using % formatting: print'"%s"'%' '.join(input().split()) \$\endgroup\$ Commented May 22, 2015 at 15:26
2
\$\begingroup\$

05AB1E, 9 bytes

#õKðý'".ø

Try it online!


# | Split on spaces.
 õK | Remove empty Strings.
 ðý | Join with spaces.
 '".ø | Surround with quotes.
answered Aug 31, 2017 at 16:52
\$\endgroup\$
2
\$\begingroup\$

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
answered Sep 1, 2017 at 9:16
\$\endgroup\$
1
\$\begingroup\$

Mathematica, 75 bytes

a=" ";b=a...;Print[InputString[]~StringReplace~{b~~"\""~~b->"\"",a..->a}]
answered May 20, 2015 at 21:05
\$\endgroup\$
1
\$\begingroup\$

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 -"
answered May 22, 2015 at 16:01
\$\endgroup\$
1
\$\begingroup\$

Octave, 44 bytes

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

Try it online!

answered Sep 21, 2017 at 23:51
\$\endgroup\$
1
\$\begingroup\$

Perl 5, 17 bytes

16 bytes of code + 1 for -p

s/ *("| ) */1ドル/g

Try it online!

answered Sep 22, 2017 at 2:09
\$\endgroup\$
1
\$\begingroup\$

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.

answered Sep 22, 2017 at 10:12
\$\endgroup\$
1
\$\begingroup\$

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

answered Sep 22, 2017 at 2:01
\$\endgroup\$
1
  • \$\begingroup\$ I caught the output issue earlier (see edit 5) but didn't notice the input issue. The command is fixed now. Thanks! \$\endgroup\$ Commented Sep 22, 2017 at 14:30
1
\$\begingroup\$

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!

(削除ここまで)

answered Sep 22, 2017 at 0:18
\$\endgroup\$
1
  • \$\begingroup\$ @KevinCruijssen Fixed. unfortunately, at the expense of many bytes. Tks for telling me. \$\endgroup\$ Commented Sep 22, 2017 at 22:25
1
\$\begingroup\$

Japt -Q, (削除) 10 (削除ここまで) 4 bytes

 ̧f ̧

Try it

answered Aug 31, 2017 at 16:33
\$\endgroup\$
1
\$\begingroup\$

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.

answered Aug 26, 2019 at 18:40
\$\endgroup\$
1
\$\begingroup\$

GolfScript, 8 bytes

' '%' '*

Try it online!

Explanation

The logic is quite simple:

' '% # Split on spaces, remove empty results
 ' '* # Join on spaces
answered Jan 9, 2020 at 14:39
\$\endgroup\$
1
\$\begingroup\$

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!

answered Jan 23, 2021 at 22:45
\$\endgroup\$
1
\$\begingroup\$

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!

answered Mar 15, 2021 at 8:53
\$\endgroup\$
1
\$\begingroup\$

K (ngn/k), (削除) 21 (削除ここまで) (削除) 18 (削除ここまで) (削除) 16 (削除ここまで) 15 bytes

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

Try it online!

  • " "\ split (implicit) input on spaces
  • (~#:')_ drop empty strings
  • " "/ join remaining items with spaces
answered Dec 1, 2020 at 22:33
\$\endgroup\$
1
\$\begingroup\$

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 (削除ここまで)

answered Dec 2, 2020 at 3:14
\$\endgroup\$
2
  • \$\begingroup\$ Other ideas failed! print* always prints a leading space and a new line. Writing to a new string (avoiding formatting directives) is annoying because gfortran fills it with garbage! Sigh \$\endgroup\$ Commented Dec 8, 2020 at 12:47
  • \$\begingroup\$ ...but fput is awesome. \$\endgroup\$ Commented Mar 12, 2021 at 10:00
1
\$\begingroup\$

ARBLE, 26 bytes

join(explode(s,"%S+")," ")

explode groups by non-spaces, and then join re-concatenates them.

Try it online!

answered Aug 15, 2023 at 22:26
\$\endgroup\$
1
\$\begingroup\$

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
answered Aug 16, 2023 at 6:15
\$\endgroup\$
0
\$\begingroup\$

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)
answered May 20, 2015 at 16:46
\$\endgroup\$
0
\$\begingroup\$

Cobra - 68

As an anonymous function:

do
 print'"[(for s in Console.readLine.split where''<s).join(' ')]"'
answered May 21, 2015 at 6:28
\$\endgroup\$
1
2

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.