17
\$\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.

\$\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\$
    – blutorange
    May 20, 2015 at 15:35
  • \$\begingroup\$ @blutorange , Yes. Edited to clarify it. \$\endgroup\$
    – Spikatrix
    May 20, 2015 at 15:36
  • 2
    \$\begingroup\$ " "aa" " --> ""aa"" (are quotes valid inside the input string?) \$\endgroup\$
    – edc65
    May 20, 2015 at 15:36
  • \$\begingroup\$ @edc65 , Good point. The answer to that is no. Edited to clarify it. \$\endgroup\$
    – Spikatrix
    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\$
    – manatwork
    May 22, 2015 at 10:49

39 Answers 39

1
2
0
\$\begingroup\$

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];
}
\$\endgroup\$
0
\$\begingroup\$

Bash ,14 bytes

read f;echo $f       # assume f="this  is  a    string   "
\$\endgroup\$
1
  • 1
    \$\begingroup\$ What about assuming “ foo * bar ” or anything else with a wildcard character? \$\endgroup\$
    – manatwork
    May 23, 2015 at 14:01
0
\$\begingroup\$

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

\$\endgroup\$
1
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Husk, 5 bytes

sJ' w

Try it online!

Fully ascii!

Explanation

sJ' w
    w split into words
 J'   join with spaces
s     add quotes
\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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