我有一个包含大写和小写字母的数组。我试图将大写字母与新数组中的以下小写字母连接起来。例如,我有以下数组
first_array = ["A","b","C","d","e"]
我希望获得以下数组
["Ab","Cde"] #new array
我试图使用如下代码迭代第一个数组:
new_array = []
first_array.each_with_index do |a,index|
if (a!~/^[a-z].*$/)
new_array = new_array.push "#{a}"
else
new_array[-1] = first_array[index-1] + "#{a}" #the idea is to concatenate the small letter with the previous capital letter and replace the last item in the new array
end
但它不起作用。我不确定我是否有效地解决了这个问题,这就是为什么我无法解决它。有人可以提出一些选择吗?
答案 0 :(得分:3)
如果您以字符串形式加入,则可以扫描以获取所有匹配项:
<input type="text" th:field="*{age}" required="required" th:attr="data-errormessage-value-missing=${#fields.errors('age')}, data-errormessage=${#fields.errors('age')}" />
答案 1 :(得分:1)
虽然我更喜欢@Paul的答案,但你可以做到以下几点。
first_array.slice_before { |s| s.upcase == s }.map(&:join)
#=> ["Ab", "Cde"]
答案 2 :(得分:0)
那么,当下一个char为大写时,你想分割原始数组,然后创建这些子数组的字符串? a method in standard lib可以帮助您:
first_array = ["A","b","C","d","e"]
result = first_array.slice_when do |a, b|
a_lower = a.downcase == a
b_upper = b.upcase == b
a_lower && b_upper
end.map(&:join)
result # => ["Ab", "Cde"]
答案 3 :(得分:0)
我非常喜欢塞尔吉奥的答案,这是我在尝试时酿造的东西:
def append_if_present(lowercase, letters)
lowercase << letters.join if letters.size > 0
end
first_array = ["A","b","C","d","e"]
capitals = []
lowercase = []
letters = []
first_array.each_with_index do |l, i|
if l =~ /[A-Z]/
capitals << l
append_if_present(lowercase, letters)
letters = []
else
letters << l
end
end
append_if_present(lowercase, letters)
p capitals.zip(lowercase).map(&:join)
答案 4 :(得分:0)
这是一种使用Enumerable#slice_when的方法:
first_array.slice_when{ |a, b| b.upcase == b && a.downcase == a }.map(&:join)