从字符串中剥离多余的空格


12

给您一个字符串。输出每个单词一个空格的字符串。

挑战

输入将是一个字符串(不null或空),用引号(包围")经由发送stdin。删除其中的前导和尾随空格。此外,如果两个单词(或符号或其他符号)之间有一个以上的空格,请将其修剪为一个空格。输出带引号的修改后的字符串。

规则

  • 字符串的长度不能超过100个字符,并且只能包含(空格)到~(波浪号)(字符代码0x20到0x7E,包括两端)范围内的ASCII字符",即,该字符串将不包含引号(")和其他字符。上面指定的范围。请参阅ASCII表以获取参考。
  • 您必须从stdin(或最接近的替代方法)获取输入。
  • 输出必须包含quotes(")。
  • 您可以编写一个完整的程序,也可以编写一个接受输入(来自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 2015年

@blutorange,是的。编辑以澄清它。
Spikatrix

2
" "aa" "-> ""aa""(输入字符串中的引号是否有效?)
edc65

@ edc65,很好。答案是否定的。编辑以澄清它。
Spikatrix 2015年

请参阅MickeyT对我的回答的评论。他的建议有效吗?在R中,返回的结果被隐式打印,但是在我的回答中,我已显式打印到stdout。
Alex A.

Answers:


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.

这也删除了尾随和前导空格

在这里在线尝试



6

Perl,22岁

(20个字节的代码,加上2个命令行开关)

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

需要使用-np开关运行,以便$_通过stdin自动填充并打印到stdout。我将假定这将字节数加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个空格字符

测试用例:

在此处输入图片说明


1
您可以替换ARGV$*保存两个字节。gsub /\s+/, ' '可以替换squeeze ' '为另外4个字节
DickieBoy

@DickieBoy,谢谢你$*,我不知道。但是我们不能gsub /\s+/, ' '它们代替,squeeze因为它们不一样
Sheharyar 2015年

“不一样”是什么意思?输出是相同的。
DickieBoy

1
squeeze ' '只会挤压空间。"yellow moon".squeeze "l" => "yelow moon"
DickieBoy

2
我个人是。还有其他一些答复者。但是,正如我所看到的,你们都不是一个人的解释……我们欢迎问题负责人做出澄清。顺便说一下,p参数之间和参数之间的空间squeeze都是不必要的。
manatwork

4

Pyth,17 15 11 10字节

(感谢YpnypnFryAmTheEggman

pjd-cQdkNN

可能会打更多的高尔夫球。

如果输出可以'代替使用,"那么我只需要8个字节:

`jd-cQdk

您可以使用N,而不是\"
Ypnypn

欢迎来到Tylio,Pyth。通过使用可以缩短第二个程序d
isaacg 2015年

@isaacg还没有d用完吗?
蒂洛

@Tyilo我认为您在我评论的大约同一时间进行了编辑。现在一切都很好。
isaacg 2015年

您可以用来p在字符串连接上节省一些字节,而不是许多+es。pjd-cQdkNN
FryAmTheEggman 2015年

3

Bash,36 32字节

作为功​​能,程序或仅在管道中:

xargs|xargs|xargs -i echo '"{}"'

说明

第一个xargs去除引号。

第二个xargs修剪左侧,并通过取每个“单词”并将每个空格分隔开来用一个空格替换字符串中间的多个相邻空格。

xargs -i echo '"{}"'修剪右侧rewraps在双引号中生成的字符串。


2
哇!那很棘手。不幸的是,它不处理测试用例4,但仍然令人印象深刻。
manatwork

是的,此代码符合第四个测试用例,并且更短。
Deltik

你可以做这样的事情吗?x=xargs;$x|$x|$x -i echo '"{}"'
Cyoce'9

@Cyoce:您确实可以这样做,以节省一个字节为代价,但是会丢失管道功能。仍然不如该解决方案那么短,并且仍然不能满足第四个测试用例。
Deltik '17

3

Haskell,31个 25字节

fmap(unwords.words)readLn

words将字符串拆分为以空格作为定界符unwords的字符串列表,并在字符串列表之间添加一个空格。引号"由Haskell的readshow(隐式地通过REPL)函数在字符串上去除并放回。

函数本身的输出长三个字节,即28个字节:

print.unwords.words=<<readLn

编辑:@Mauris指向该readLn函数,它节省了一些字节。


Parse error: naked expression at top level当我在这里
Spikatrix

@CoolGuy:rextester.com需要整个程序,而不是功能,因此请尝试main=interact$show.unwords.words.readhaskell.org的正面有一个在线REPL (需要启用cookie),您可以在其中进行尝试fmap(unwords.words.read)getLine
nimi 2015年

1
fmap(unwords.words)readLn而且print.unwords.words=<<readLn有点短。
林恩

@Mauris:感谢您指向readLn
nimi 2015年

2

R,45个字节

cat('"',gsub(" +"," ",readline()),'"',sep="")

readline()函数从STDIN读取,自动剥离所有前导和尾随空格。使用删除单词之间的多余空格gsub()。最后,在双引号前加上和将结果加到STDOUT。

例子:

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

不知道它是否完全符合规则,但是可能不一定完全需要cat,而只是gsub。其输出是[1] "This is a string"
MickyT 2015年

@MickyT:谢谢你的建议。根据OP的评论(我首先发表),我的解释是必须将其打印到stdout。我会要求澄清。
Alex A.

啊...没看到这个评论或要求
MickyT

2

Python2,37

@ygramul减少了1个字节。

print'"%s"'%' '.join(input().split())

原始版本:

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

测试用例:

测试案例截图


我真的很想使用print" ".join(raw_input().split()),但是如果在最后一个引号后面有空格,那么它将在最后一个引号内包含尾随空格...
mbomb007 2015年

您可以使用%格式
删除

2

JavaScript(ES6),49 52 58

多亏@Optimizer,编辑短6个字节

编辑2 -3,感谢@nderscore

通过弹出窗口输入/输出。使用模板字符串在字符串连接中削减1个字节。

运行代码段以在Firefox中进行测试。

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


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

@Optimizer thx。请注意,这只是最后的澄清引号后的工作原理:的eval(“””““)将崩溃。
edc65

当我测试第四个测试用例(使用chrome)时,没有看到弹出窗口(显示结果)。为什么?
Spikatrix

@CoolGuy也许是因为Chrome无法运行ES6?我从不使用Chrome测试ES6。无论如何,我现在都在Chrome(42.0.2311.152)中尝试了它,并为我工作。
edc65

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



1

KDB(Q),28个字节

" "sv except[;enlist""]" "vs

说明

                       " "vs    / cut string by space
      except[;enlist""]         / clear empty strings
" "sv                           / join back with space

测试

q)" "sv except[;enlist""]" "vs"12 34  ~5 6   (7, 8) - 9 -  "
"12 34 ~5 6 (7, 8) - 9 -"

1

Java 8,43字节

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

说明:

在这里尝试。

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字节

split(" ")|map(select(length>0))|join(" ")

样品运行

$ 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

在线尝试


我较早地发现了输出问题(请参阅编辑5),但是没有注意到输入问题。该命令现已修复。谢谢!
jq170727

1

Tcl,69字节

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

在线尝试!

Tcl,79字节

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

在线尝试!


@KevinCruijssen固定。不幸的是,以许多字节为代价。谢谢你告诉我。
sergiol


0

golfua,42个字节

L=I.r():g('%s*\"%s*','"'):g('%s+',' ')w(L)

简单模式匹配替换:找到\"用0或多个空格()包围的任何双引号()%s*并返回单引号,然后用单个空格替换所有1个或多个空格(%s+)。

相当于Lua

Line = io.read()
NoSpaceQuotes = Line:gsub('%s*\"%s*', '"')
NoExtraSpaces = NoSpaceQuotes:gsub('%s+', ' ')
print(NoExtraSpaces)

0

眼镜蛇-68

作为匿名函数:

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

0

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

未压缩版本:

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

重击,14字节

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

1
假设“ foo * bar”或其他带有通配符的字符怎么办?
manatwork

0

Powershell,40个字节

"`"$(($args-Replace' +'," ").trim())`""

挺直的,不是很令人印象深刻。

说明

通过(预定义的)args变量获取输入参数,将所有多个空格替换为一个,使用trim()方法修剪前导和尾随空格,并添加引号。Powershell将打印字符串作为默认行为进行控制台。


0

k4,23个字节

" "/: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个字节

<<<\"${(Qz)1}\"

在线尝试!

输入字符串包含嵌入式引号。删除Q14个字节,如果输入字符串不包含嵌入式引号,因为在这里的一些其他的答案中进行。

参数扩展标志:Q取消引用,然后z像shell一样拆分为单词。然后,这些单词由空格隐式连接。


0

ren,56字节

等待。替换只有一次吗?现在,我必须使用拆分联接组合。

Fn.new{|x|x.trim().split(" ").where{|i|i!=""}.join(" ")}

在线尝试!

说明

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个字节

' '%' '*

在线尝试!

说明

逻辑很简单:

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

-1

Python2,28个字节

lambda s:" ".join(s.split())

说明

lambda s

以s为输入的匿名函数。

s.split()

返回字符串s的单词列表(由空格字符任意字符串分隔)。

" ".join(...)

将列表重新连接成字符串,每个单词用空格(“”)分隔。


2
对于前导空格和尾随空格,这似乎给出了不正确的结果。请注意,在挑战状态下,您应将输入带双引号,并将输出也带双引号。一开始我也有这个错误,直到我重新阅读挑战。
凯文·克鲁伊森
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.