【发布时间】:2016-12-12 01:42:44
【问题描述】:
所以我试图遍历一个字符串并根据偏移量替换每个字母数字字符。
我想要这样的东西:
"abc 123 !@#$%",偏移量为
1: "bcd 234 !@#$%"
2: "cde 345 !@#$%"
我的代码的问题是它不会修改字符串。
alphabets = [*?a..?z] #makes an array of all the alphabets
digits = [*?0..?9] #makes an array of all the single digits
puts "offset?"
offset = gets.chomp.to_i
puts "string?"
string = gets.chomp
string.each_char do |character|
if character[/[a-zA-Z]/] == character #checks if the character is an alphabet
char_index = alphabets.index(character) + offset #gets the index of the current character being iterated and adds the offset
#if the (index + offset) % 26 > 0, that means that the index is beyond 25.
#Then it will find the remainder and apply that as the new index
char_index = char_index % 26 if char_index % 26 >= 0
character.sub!(character, alphabets[char_index]) #replaces the character with the offset character
elsif character[/\d/] == character #checks if the character is a number
char_index = digits.index(character) + offset
char_index = char_index % 10 if char_index % 10 >= 0
character.sub!(character, digits[char_index])
end
#if the character is neither an alphabet nor a number, nothing will run for that character
end
puts string
【问题讨论】:
-
具体说明您遇到的问题
-
程序打印的是原始字符串,而不是修改后的字符串。
-
您只是在更改字符,而不是在原始字符串上替换它。