文字列から余分なスペースを取り除く


12

文字列が与えられます。単語ごとに1つのスペースを含む文字列を出力します。

チャレンジ

入力は、を介して送信されたnullquotes(")で囲まれた文字列(not またはempty)になりstdinます。先頭と末尾のスペースを削除します。また、2つの単語(または記号など)の間に複数のスペースがある場合は、1つのスペースにトリミングします。変更された文字列を引用符付きで出力します。

ルール

  • 文字列は100文字を超えず、範囲(スペース)から~(チルダ)(文字コード0x20から0x7Eを含む)のASCII文字のみを含みます"。つまり、文字列には引用符が含まれません(")およびその他の文字上記で指定された範囲。リファレンスについては、ASCIIテーブルを参照してください。
  • から入力を取得する必要があります stdin(または最も近い代替)。
  • 出力には引用符が含まれている必要があります(")。
  • 完全なプログラム、または入力を受け取る関数( stdin)を受け取り、最終的な文字列を出力ます

テストケース

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

得点

これはコードゴルフなので、最短の提出(バイト単位)が勝ちです。


1
あなたが言いmust take input from stdin、後で言う...or a function which takes input, and outputs the final string。これは、関数stdinも入力を受け取る必要があるということですか?
ブルトレンジ

@blutorange、はい。明確にするために編集されました。
Spikatrix

2
" "aa" "-> ""aa""(引用符は入力文字列内で有効ですか?)
edc65

@ edc65、良い点。それに対する答えはノーです。明確にするために編集されました。
Spikatrix

私の答えに対するMickeyTのコメントをご覧ください。彼が提案したことは有効ですか?Rでは、返された結果は暗黙的に出力されますが、私の答えでは、stdoutに明示的に出力しました。
アレックスA.

回答:


12

CJam、7バイト

q~S%S*p

コードの説明

CJamはすべての大文字を組み込み変数として予約しています。だから、Sここではスペースの価値を持っています。

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.

これにより、末尾と先頭のスペースも削除されます

こちらからオンラインでお試しください


10

///:18文字

/  / //" /"// "/"/

サンプル実行:

(使用faubiguy「彼からの通訳をPerlの答えのためのスラッシュ『)(発音///解釈』。)

bash-4.3$ ( echo -n '/  / //" /"// "/"/'; echo '"   foo  *  bar   "'; ) | slashes.pl
"foo * bar"


技術的には、入力を受け付けていません。;)この言語はありますが、入力を読むことはまだかなり苦痛だと思います。
マーティンエンダー

6

Perl、22

(20バイトのコードと2つのコマンドラインスイッチ)

s/ +/ /g;s/" | "/"/g

stdinを介して自動的に入力され、stdoutに出力されるように、-npスイッチで実行する必要があります$_。これにより、バイトカウントに2が追加されると仮定します。


1
同じ解決策:sed -E 's/ +/ /g;s/" | "/"/g'
izabera

3
同じことはRetinaの 12バイトです。:)
マーティンエンダー

-pを意味する-nので、ここで+1のペナルティを受けるだけです(他のコメンターが提案するように、単に別の言語に切り替えないことを前提としています)。

4

Ruby、31 29 25 23バイト

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

コードの説明:

  • pに二重引用符で囲まれた文字列を出力しますSTDOUT(ただし、他にもあります...)
  • $*STDIN入力の配列で$*[0]、最初のものを受け取ります
  • strip 開始スペースと終了スペースを削除します
  • squeeze ' ' 1個以上のスペース文字を単一のスペースに置き換えます

テストケース:

enter image description here


1
You can replace ARGV with $* saving two bytes. gsub /\s+/, ' ' can be replaced with squeeze ' ' for another 4 bytes
DickieBoy

@DickieBoy, thank you for $*, I didn't know that. But we can't replace gsub /\s+/, ' ' with squeeze because they are not the same.
Sheharyar

What do you mean by "are not the same"? The outputs are the same.
DickieBoy

1
squeeze ' ' will only squeeze spaces. "yellow moon".squeeze "l" => "yelow moon"
DickieBoy

2
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.
manatwork

4

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

You can use N instead of \"
Ypnypn

Welcome to Pyth, Tylio. The second program could be shorterned by the use of d.
isaacg

@isaacg haven't I already used d for everything it can be used for?
Tyilo

@Tyilo I think you made an edit at about the same time I commented. It's all good now.
isaacg

You can use p to save a few bytes on string concatenation instead of many +es. pjd-cQdkNN
FryAmTheEggman

3

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.


2
Wow! That is tricky. Unfortunately not handles test case 4, but still impressing.
manatwork

Yeah, this code meets the fourth test case and is shorter.
Deltik

Can you do something like this? x=xargs;$x|$x|$x -i echo '"{}"'
Cyoce

@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.
Deltik

3

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.


I'm getting Parse error: naked expression at top level when I tested both the codes here
Spikatrix

@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

1
fmap(unwords.words)readLn and print.unwords.words=<<readLn are a bit shorter.
Lynn

@Mauris: thanks for pointing to readLn.
nimi

2

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

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

@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.

Ahhh ... didn't see that comment or requirement
MickyT

2

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


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

You can shave off an extra byte using % formatting: print'"%s"'%' '.join(input().split())
ygramul

2

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


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

@Optimizer thx. Note, that just works after the last clarification about the quotes: eval('" " "') would crash.
edc65

When I tested the fourth test case (using chrome), no popup (which shows the result) is seen. Why?
Spikatrix

@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

-3: alert(`"${prompt().match(/[^ "]+/g).join(" ")}"`)
nderscore



1

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

1

Java 8, 43 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
                   |\"",      //     and all quotes
                        " ")  //    with a single space
    .trim()                   //  And remove all leading and trailing spaces
  +'"'                        //  And add the trailing quote
                              // End of method (implicit / single-line return statement)



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

Try it online


I caught the output issue earlier (see edit 5) but didn't notice the input issue. The command is fixed now. Thanks!
jq170727

1

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!


@KevinCruijssen Fixed. unfortunately, at the expense of many bytes. Tks for telling me.
sergiol


0

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)

0

Cobra - 68

As an anonymous function:

do
    print'"[(for s in Console.readLine.split where''<s).join(' ')]"'

0

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

0

Bash ,14 bytes

read f;echo $f       # assume f="this  is  a    string   "

1
What about assuming “ foo * bar ” or anything else with a wildcard character?
manatwork

0

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.


0

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

0

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.


0

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

0

GolfScript, 8 bytes

' '%' '*

Try it online!

Explanation

The logic is quite simple:

' '%     # Split on spaces, remove empty results
    ' '* # Join on spaces

-1

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


2
This seems to give incorrect results regarding leading and trailing spaces. Note that the challenge state you should take the input with the double-quotes, and also output them with double-quotes. I also had this wrong at first, until I re-read the challenge.
Kevin Cruijssen
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.