给定一个字符串,我们必须在Ruby中反转该字符串。
Ruby为您提供了方法reverse来反转字符串,但是您也可以通过使用代码来执行相同的功能。在以下程序中,我们提到了查找字符串反向的两种方法。
使用的方法:
puts:用于向用户传达消息。
gets:用于接受用户的输入。
.length:用于获取字符串的长度。
.reverse:这是预定义的方法,专门用于查找字符串的反向。您可以使用此方法直接在单个代码中找到字符串的反向。
使用的变量:
str1:存储用户提供的字符串。
newstr:存储与实际字符串相反的新字符串。
方法(1):不使用库方法
=begin
Ruby program to reverse a given string.
=end
puts "Enter the String:"
str1=gets.chomp
newstr= ' '
for i in 1..str1.length
newstr+=str1[str1.length - i]
end
puts "The reverse of #{str1} is #{newstr}"输出结果
RUN 1: Enter the String: Nhooo.com The reverse of Nhooo.com is moc.ooohN RUN2: Enter the String: Hrithik The reverse of Hrithik is kihtirH
方法(2):使用反向字符串
=begin
Ruby program to reverse a given string.
=end
puts "Enter the String:"
str1=gets.chomp
newstr=str1.reverse
puts "The reverse of #{str1} is #{newstr}"输出结果
RUN 1: Enter the String: Nhooo The reverse of Nhooo is ooohN RUN 2: Enter the String: Haridwar The reverse of Haridwar is rawdiraH