w3resource

Ruby String Exercises: Count the occurrences of a specified character in a given string

Ruby String: Exercise-10 with Solution

Write a Ruby program to count the occurrences of a specified character in a given string.

Ruby String Exercises: Count the occurrences of a specified character in a given string

Ruby Code:

def check_string(my_string, chr)
   return my_string.count(chr) 
end
print check_string("JavaScript", "J")
print "\n",check_string("JavaScript", "a")
print "\n",check_string("JavaScript", "S")

Output:

1
2
1

Flowchart:

Flowchart: Count the occurrences of a specified character in a given string

Ruby Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Ruby program to check whether a string starts with an other string.
Next: Write a Ruby program to sort a string's characters alphabetically.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/ruby-exercises/string/ruby-string-exercise-10.php