【问题标题】:I would like to retrieve words with their number of characters我想用字符数检索单词
【发布时间】:2021-07-10 06:25:22
【问题描述】:

就像标题一样。我想用 Ruby 检索带有字符数的单词。我搜索了很多,有很多方法可以选择数组中的元素。但是是否可以仅恢复数组中包含 5 个字符的字符串?

提前谢谢你!

【问题讨论】:

  • “我的数组中包含 5 个字符的字符串”——这个数组长什么样?请出示相应的代码。

标签: arrays ruby string


【解决方案1】:

当然,这样的东西可以工作

words_with_five_characters = words.select { |w| w.length == 5 }

【讨论】:

    【解决方案2】:

    我假设您已经将您的标题转换为 array 的单词,在这种情况下,@Ursus 的答案是完美的。

    如果有帮助,您也可以直接从string 开始,使用scan 和正则表达式来识别5 个字母的单词:

    title = 'this is my title and it has a lot of words including some longer than five characters'
    title.scan(/\b\w{5}\b/)
    => ["title", "words"]
    

    【讨论】:

    • /\w{5}/ 不考虑单词边界——它只匹配 5 个连续的字母数字字符,例如"developers".scan(/\w{5}/) 返回["devel", "opers"]
    • 你说的完全正确,我忘了添加它们!我正在相应地编辑我的答案。谢谢@Stefan
    猜你喜欢
    • 2014-08-09
    • 2023-01-14
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    相关资源
    最近更新 更多