ruby - 将字符串分割成 block (不同大小)而不破坏单词

标签 ruby string

我正在尝试创建一个方法,给定一个字符串,返回三个字符串:标题、描述1、描述2

这是我发现的一个相关问题:Split a string into chunks of specified size without breaking words - 但我的 block 大小不同。

标题不得超过 25 个字符。

描述 1 最多需要 35 个字符。

描述 2 最多需要 35 个字符。

问题是:

如何分割一个字符串,以便它最多创建三个实体(注意:如果该字符串只能容纳第一个实体,那么我不需要返回三个实体),其中第一个实体最多包含 25 个字符,另外两个实体每个最多包含 35 个字符。使该方法足够聪明,能够考虑单词(也许还有标点符号),这样它就不会返回剪切结果。

我已完成以下操作:

def split_text_to_entities(big_string)
  title = big_string(0..24)
  description1 = big_string(25..59)
  description2 = big_string(60..94)
end

但这种方法的问题在于,如果输入是“从我们的商店购买我们的新品牌鞋子。镇上最好的折扣,首次购买可享受 40% 的折扣。”,结果将是:

title = "Buy our new brand shoes f"
description1 = "rom our store. Best discounts in to"
description2 = "wn and 40% off for first purchase."

理想情况下它们应该是:

title = "Buy our new brand shoes"
description1 = "from our store. Best discounts in"
description2 = "town and 40% off for first"

因此,请尝试按字符大小进行拆分,同时考虑到单词。

最佳答案

为了涵盖所有基础,我会执行以下操作。

代码

def divide_text(str, max_chars)
  max_chars.map do |n|
    str.lstrip!
    s = str[/^.{,#{n}}(?=\b)/] || ''
    str = str[s.size..-1]
    s
  end
end

(?=\b) 是与分词符匹配的(零宽度)正向前瞻。

示例

max_nbr_chars = [25,35,35]

str = "Buy our new brand shoes from our store. Best discounts in " +
      "town and 40% off for first purchase."    
divide_text(str, max_nbr_chars)
  #=> ["Buy our new brand shoes",
  #    "from our store. Best discounts in",
  #    "town and 40% off for first"]

str = "Buy our new brand shoes from our store."
divide_text(str, max_nbr_chars)
  #=> ["Buy our new brand shoes", "from our store.", ""]

str = "Buy our new"
divide_text(str, max_nbr_chars)
  #=> ["Buy our new", "", ""]

str = ""
divide_text(str, max_nbr_chars)
  #=> ["", "", ""]

str = "Buyournewbrandshoesfromourstore."
divide_text(str, max_nbr_chars)
  #=> ["", "Buyournewbrandshoesfromourstore.", ""]

str = "Buyournewbrandshoesfromourstoreandshoesfromourstore."
divide_text(str, max_nbr_chars)
  #=> ["", "", ""]

请注意,如果正则表达式中省略 ^:

str = "Buyournewbrandshoesfromourstore."
divide_text(str, max_nbr_chars)
  #=> ["ewbrandshoesfromourstore.", "rstore.", ""]

关于ruby - 将字符串分割成 block (不同大小)而不破坏单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24871475/

相关文章:

ruby-on-rails - 我如何在 Rails 3 插件中测试路由?

ruby-on-rails - Nokogiri XML 文件输出位于何处?

arrays - 分割数组的每一项

string - KMP模式匹配算法的时间复杂度可以是O(m*n)?

python - 如何获取每个字符串变体以及每个位置的可能性列表

ruby - ruby 脚本中的 CSS 选择器和条件

ruby-on-rails - ActiveRecord 模型测试的性能

python - Python中的“就地”字符串修改

php - 与 nl2br 类似的函数,但使用 <w :br/> tags and removing any break lines

javascript - 我在 JavaScript 中有一个 JSON 对象,想要从字符串变量访问键