Ruby程序反向字符串
反转字符串
给定一个字符串,我们必须在Ruby中反转该字符串。
Ruby为您提供了方法reverse来反转字符串,但是您也可以通过使用代码来执行相同的功能。在以下程序中,我们提到了查找字符串反向的两种方法。
使用的方法:
puts:用于向用户传达消息。
gets:用于接受用户的输入。
.length:用于获取字符串的长度。
.reverse:这是预定义的方法,专门用于查找字符串的反向。您可以使用此方法直接在单个代码中找到字符串的反向。
使用的变量:
str1:存储用户提供的字符串。
newstr:存储与实际字符串相反的新字符串。
Ruby代码反转字符串
方法(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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短