在Ruby中将每个单词的每个n个字符大写

时间:2018-08-05 19:01:30

标签: ruby string uppercase

我需要为字符串中的每个单词大写每个“第n个”字符(在此示例中,第4个字符的倍数,因此字符4、8、12等)。

我想出了下面的代码(我知道不是很优雅!),但是它仅适用于length < 8的单词。

'capitalize every fourth character in this string'.split(' ').map do |word|
  word.split('').map.with_index do |l,idx|
  idx % 3 == 0 && idx > 0 ? word[idx].upcase : l 
  end 
  .join('')
end 
.flatten.join(' ')

任何人都可以告诉我如何将长度大于8的单词中的第4个字符大写吗?

谢谢!

4 个答案:

答案 0 :(得分:4)

作为选择,您可以仅通过按索引访问字符来修改字符串中的第n个字符(如果存在)。

'capitalizinga every fourth character in this string'.split(' ').map do |word|
  (3..word.length).step(4) do |x|
    c = word[x]
    word[x] = c.upcase if c
  end
  word
end.join(' ')

# capItalIzinGa eveRy fouRth chaRactEr in thiS strIng

这里使用的是方法stepRange类,因此可以计算每个第四个索引:3、7、11等...

答案 1 :(得分:4)

str = 'capitalize every fourth character in this string'

idx = 0
str.gsub(/./) do |c|
  case c
  when ' '
    idx = 0
    c
  else
    idx += 1
    (idx % 4).zero? ? c.upcase : c
  end
end
  #=> "capItalIze eveRy fouRth chaRactEr in thiS strIng"

答案 2 :(得分:3)

我认为最简单的方法是使用带有替换的正则表达式:

'capitalize every fourth character in this string'
  .gsub(/([\w]{3})(\w)|([\w]{1,3})/) {
    "#{$1}#{$2.to_s.upcase}#{$3}"
  }

# => capItalIze eveRy fouRth chaRactEr in thiS strIng

这会使用2个带有捕获组的替代方案-第一个替代方案匹配4个字符,第二个替代方案匹配1-3个字符。 $1组将完全匹配三个字母,而$2组将匹配四个字母的第四个字母-而$3组将匹配较长单词的剩余部分以及短于4个字符的单词。 然后,可以用$2全局替换组gsub。另外,如果$2.to_s$2,则需要执行nil(或使用三元运算符捕获该情况)。

您可以检查正则表达式here并尝试代码here

答案 3 :(得分:1)

> str.split(" ").map{|word| 
    word.chars.each_with_index{|c,i| 
      c.upcase! if (i > 0 && (i+1)%4 == 0)}.join}.join(" ")
#=> "capItalIze eveRy fouRth chaRactEr in thiS strIng"
相关问题