简体   繁体   English

每次出现特定字符时都会拆分一个字符串吗?

[英]Split a string at every occurrence of particular character?

I would like to pass a sequence of characters into a function as a string and have it return to me that string split at the following characters: 我想将一个字符序列作为字符串传递给函数,并让我将字符串拆分为以下字符:

@ # $ % ^ & *

such that if the string is 这样,如果字符串是

'hey#man^you*are#awesome'

the program returns 程序返回

'hey man you are awesome' “嘿,你真棒”

How can I do this? 我怎样才能做到这一点?

To split the string you can use String#split 要分割字符串,可以使用String#split

'hey#man^you*are#awesome'.split(/[@#$%^&*]/)
#=> ["hey", "man", "you", "are", "awesome"]

to bring it back together, you can use Array#join 将其重新组合在一起,可以使用Array#join

'hey#man^you*are#awesome'.split(/[@#$%^&*]/).join(' ')
#=> "hey man you are awesome"

split and join should be self-explanatory. splitjoin应该是不言自明的。 The interesting part is the regular expression /[@#$%^&*]/ which matches any of the characters inside the character class [...] . 有趣的部分是正则表达式/[@#$%^&*]/ ,它匹配字符类[...]中的任何字符。 The above code is essentially equivalent to 上面的代码基本上等同于

'hey#man^you*are#awesome'.gsub(/[@#$%^&*]/, ' ')
#=> "hey man you are awesome"

where the gsub means "globally substitute any occurence of @#$%^&* with a space". 其中gsub意思是“用gsub将@#$%^&*的所有出现位置全局替换”。

You could also use String#tr , which avoids the need to convert an array back to a string: 您还可以使用String#tr ,这避免了将数组转换回字符串的需要:

'hey#man^you*are#awesome'.tr('@#$%^&*', '       ')
  #=> "hey man you are awesome" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM