Take the 2-minute tour ×
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.

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.

share|improve this question
    
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? –  blutorange yesterday
    
@blutorange , Yes. Edited to clarify it. –  Cool Guy yesterday
1  
" "aa" " --> ""aa"" (are quotes valid inside the input string?) –  edc65 yesterday
    
@edc65 , Good point. The answer to that is no. Edited to clarify it. –  Cool Guy yesterday
    
Please see MickeyT's comment on my answer. Is what he proposes valid? In R, returned results are implicitly printed, but in my answer I've explicitly printed to stdout. –  Alex A. yesterday

13 Answers 13

up vote 10 down vote accepted

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

share|improve this answer

///: 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"
share|improve this answer
8  
    
Technically you're not taking input though. ;) There's this language but reading input is still quite a pain I think. –  Martin Büttner yesterday

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.

share|improve this answer
1  
same solution: sed -E 's/ +/ /g;s/" | "/"/g' –  izabera yesterday
2  
The same thing is 12 bytes in Retina. :) –  Martin Büttner yesterday

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.

share|improve this answer
    
Wow! That is tricky. Unfortunately not handles test case 4, but still impressing. –  manatwork 17 hours ago
    
Yeah, this code meets the fourth test case and is shorter. –  Deltik 14 hours ago

Pyth, 17 15 11 bytes

+N+jd-cQdkN

Could probably be golfed more.

If the output can use ' instead of " then I only need 8 bytes:

`jd-cQdk
share|improve this answer
    
You can use N instead of \" –  Ypnypn yesterday
    
@Ypnypn thanks :) –  Tyilo 17 hours ago
    
Welcome to Pyth, Tylio. The second program could be shorterned by the use of d. –  isaacg 17 hours ago

JavaScript (ES6), 52 58

Edit 6 bytes shorter, thanks to @Optimizer

Input/output via popup. Using template string to cut 1 byte in string concatenation.

Run snippet to test in Firefox.

alert(`"${eval(prompt()).match(/\S+/g).join(" ")}"`)

share|improve this answer
    
alert(`"${eval(prompt()).match(/\S+/g).join(" ")}"`) - 52 –  Optimizer yesterday
    
@Optimizer thx. Note, that just works after the last clarification about the quotes: eval('" " "') would crash. –  edc65 yesterday
    
When I tested the fourth test case (using chrome), no popup (which shows the result) is seen. Why? –  Cool Guy 16 hours ago
    
@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. –  edc65 13 hours ago

Python2, 38

print'"'+' '.join(input().split())+'"'

Test cases:

Test cases screenshot

share|improve this answer
    
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... –  mbomb007 yesterday

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 -"
share|improve this answer
    
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" –  MickyT yesterday
    
@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. –  Alex A. yesterday
    
Ahhh ... didn't see that comment or requirement –  MickyT yesterday

Haskell, 31 bytes

fmap(unwords.words.read)getLine

Applies first read, then words and then unwords to the string read from stdin via getLine. read removes the surrounding ", words splits the string into a list of strings with spaces as delimiters and unwords joins the list of strings with spaces in-between.

Output is done via the REPL. Outputting by the function itself is one byte longer, i.e. 32 bytes:

interact$show.unwords.words.read
share|improve this answer
    
I'm getting Parse error: naked expression at top level when I tested both the codes here –  Cool Guy 16 hours ago
    
@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. –  nimi 10 hours ago

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)
share|improve this answer

Mathematica, 75 bytes

a=" ";b=a...;Print[InputString[]~StringReplace~{b~~"\""~~b->"\"",a..->a}]
share|improve this answer

Cobra - 68

As an anonymous function:

do
    print'"[(for s in Console.readLine.split where''<s).join(' ')]"'
share|improve this answer

Ruby, 31 Bytes

p ARGV[0].strip.gsub /\s+/, ' '

Code Explanation:

  • p outputs string within double quotes to STDOUT (There's more to it though...)
  • ARGV is an array of STDIN inputs, ARGV[0] takes the first one
  • strip removes starting and ending spaces
  • gsub /\s+/, ' ' does a regex search for >1 space characters and replaces them with a single space

Test Cases:

enter image description here

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.