是否生成一个带有额外空格,字符返回或零的字符串?

问题描述 投票:0回答:2

我编写了一个代码,用于使用简单的替换密码(a = b,b = c等)将纯文本消息转换为密文消息。空格用“1”代替。

然后我想做它,以便我可以使用'gets'键入不同的消息。这导致了一个问题,我通过用“gets.strip”替换“gets”来解决这个问题。如果获取是在键入的字符串中添加一个空格,无论是在开头还是结尾,为什么它会导致问题?我有办法处理空间,所以它真的是一个“”还是一个零空间(缺少一个更好的词)或一个字符返回或什么?这就是我写的:

base_alph =[" ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]  
code_alph = ["1", "z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"]  
x=0  
base_msgarray = []  
code_msgarray = []  
puts "type what you want to translate below"  
base_msg = gets.strip # without the .strip the program doesn't run  
msg_size = base_msg.length  
puts "the message is translated as:"  

loop do  #this section populates an array with all the characters from the gets  
break if x >= msg_size  
base_msgarray.push(base_msg[x])  
x += 1  
end  
# this section passes in the values of the base_msgarray to |letter| to then determine its key   
# in base_alph then that key is passed into code_alph to find the translated letter which  
# is then used to populate the code_msgarray  
base_msgarray.each do |letter|  
code_index = base_alph.index(letter)  
code_msgarray.push(code_alph[code_index])  
end  
# this section displays the values of code_msgarray in a more text-like fashion  
code_msgarray.each do |codeletter|  
print codeletter  
end  
gets # for some reason if i dont have this here the terminal window disappears before I can read anything  
ruby gets
2个回答
0
投票

问题是这个。如果不使用strip,则会在输入中附加换行符。例如

type what you want to translate below
rubyisgreat

如果使用gets.strip,则为base_msg的值

"rubyisgreat"

没有条带的base_msg的值

"rubyisgreat\n"

因此,由于“\ n”不属于您的密码数组,因此请查询其索引

code_index = base_alph.index(letter)

产生零。这个零在下一行用作

code_msgarray.push(code_alph[code_index])

因此错误!

这是一个提示。使用'p base_msg'检查确切的值。还有一件事。您可能正在使用ruby,但您需要学习它。这个程序是用Ruby编写的。它不是红宝石的方式。在这里使用哈希而不是数组。如果可能的话,不要使用循环。


0
投票

来自fine manual

gets(sep = $ /)→string或nil [...]

返回(并分配给$_ARGV(或$*)中文件列表中的下一行,如果命令行中没有文件,则返回标准输入。在文件末尾返回nil。可选参数指定记录分隔符。分隔符包含在每条记录的内容中。

请注意最后一句:记录分隔符包含在每条记录的内容中。默认情况下,单独的记录是EOL(通常是换行符或回车符/换行符对),因此您将在字符串的位置获得一个迷路\n

您的strip调用将删除前导和尾随空格(包括CR和LF字符),因此问题就消失了。另一种常见的方法是使用chomp剥离尾随的$/记录分隔符(如果存在)。

© www.soinside.com 2019 - 2024. All rights reserved.