How to move characters from right to left of string

Mike

New Member
#1
I need to move characters from left to right of a string in combinations of two. An example input is:
Mã:
"D21635D486450000C1"
The expected output for this is:
Mã:
"C100004586D43516D2"
Any help is greatly appreciated.
I have this so far:
Mã:
str = "D21635D486450000C1"
str.length.times do |i|
 str.insert(i, str[-2-i])
end
puts str
 

Admin

Administrator
Thành viên BQT
#2
"D21635D486450000C1".chars.each_slice(2).to_a.reverse.join
#⇒ "C100004586D43516D2"
or use join(' ') on the last step to have spaces or whatever between slices.

Also:
Mã:
str = "D21635D486450000C1"
(0..str.length-1).step(2).map { |i| [str[-i-2], str[-i-1]] }.join
#⇒ "C100004586D43516D2"
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top