【问题标题】:How to remove a consecutively repeating character in a string?如何删除字符串中连续重复的字符?
【发布时间】:2016-08-31 11:06:52
【问题描述】:

考虑一下我的意见:-

"1 1 3 3 3 2 2 2 2 14 14 14 11 11 11 2"

我希望输出是

"1 3 2 14 11 2"

【问题讨论】:

  • uniq 和挤压方法...使用索引变量进行硬编码
  • @AshKashyap 向我们展示你的努力,StackOverflow 这不是为我编写代码的服务。

标签: arrays ruby string


【解决方案1】:

试试这个:

items = "1 1 3 3 3 2 2 2 2 14 14 14 11 11 11 2"

items.split(' ').chunk(&:itself).collect(&:first)

#> ["1", "3", "2", "14", "11", "2"]

【讨论】:

    【解决方案2】:
    string_data = "1 1 3 3 3 2 2 2 2 14 14 14 11 11 11 2"
    
    string_data.split(' ').chunk(&:itself).collect(&:first).join(' ')
    

    输出将是"1 3 2 14 11 2"

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 2018-08-05
      • 2016-07-31
      相关资源
      最近更新 更多