Write a Ruby program to search a string in a sentence.
class CountStringInSentence
def countOccurance
print "Enter the main sentence: "
main_string = gets.chomp
print "Enter the search string: "
search_string = gets.chomp
count = 0
main_string.split(" ").each do |s|
count = count + 1 if s.casecmp(search_string).zero?
end
print "search string '#{search_string}' occured #{count} times"
end
end
p = CountStringInSentence.new
p.countOccurance
Output:
class CountStringInSentence
def countOccurance
print "Enter the main sentence: "
main_string = gets.chomp
print "Enter the search string: "
search_string = gets.chomp
count = 0
main_string.split(" ").each do |s|
count = count + 1 if s.casecmp(search_string).zero?
end
print "search string '#{search_string}' occured #{count} times"
end
end
p = CountStringInSentence.new
p.countOccurance
Output:
Enter the main sentence: samajh samajh ke samajh ko samjho
Enter the search string: samajh
search string 'samajh' occured 3 times
|
No comments:
Post a Comment