Ruby程序计算字符串中的单词数
计算字符串中的单词
给定一个字符串,我们必须计算Ruby中字符串的单词总数。
Ruby提供了几种方法来计算字符串中单词的数量。可以实现其中一种方法,该方法要求使用.split方法将字符串转换为数组,然后继续对数组元素进行计数。但是,让我们不要陷入复杂的事情。以下代码将使您知道处理这种情况的最简单方法。
使用的方法:
puts:每个Ruby程序中最常用的方法。它用于向用户传达一些消息。
gets:用于接受用户输入。
.length:此方法返回字符串的长度。
使用的变量:
str1:保存用户输入的字符串。
count:它用作计数器,用于计算字符串中的单词数。
Ruby代码计算字符串中的单词数
=begin
Ruby program to find number of words in a string.
=end
puts "Enter the String:"
str1=gets.chomp
count=1
for i in 1..str1.length
if (str1[i] == ' ')
count+=1
end
end
puts "Number of words are #{count}"输出结果
RUN 1: Enter the String: hello guys! You are at Nhooo Number of words are 6 RUN 2: Enter the String: Destiny is powerful! Number of words are 3
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短