The task is to write a simplified version of Ruby's String#count method oneself. Simplified because it doesn't have to have the negation and sequence parts of the original.
Here my solution:
def custom_count(string, search_char)
sum = 0
seg_string = string.split("")
seg_char = search_char.split("")
for i in seg_string
for j in seg_char
if i == j
sum += 1
end
end
end
sum
end
p custom_count("Hello, World!", "l") # => 3
p custom_count("Hello, World!", "lo") # => 5
p custom_count("Hello, World!", "le") # => 4
p custom_count("Hello, World!", "x") # => 0
p custom_count("Hello, World!", "w") # => 0
p custom_count("Hello, World!", "W") # => 1
Is there a better way to solve the task? Perhaps without using nested loops?