I want to search for "s" from the following character string "t".
filename.rb
s = 'AA'
t = 'abdeeAAbAAAbfde'
Normally, I'm a fool who thought, "Hey, I can go with the count method."
filename.rb
s = 'AA'
t = 'abdeeAAbAAAbfde'
puts t.count(s)
#Expected output ➡︎ 3
#Actual output ➡︎ 5
No, I just count the number of A normally. With the count method, even if you give a set of character strings to the arguments, it seems that one character or one character will be searched.
In other words
I want to count the above three. (Transferred ...! Lol)
If you think about it by chewing, the string abdeeAAbAAAbfde Divide into ab bd de ee eA AA Ab bA AA AA Ab bf fd de It is good to verify whether it matches the character string AA, count if it is true, and not count if it is false.
※point Specify the range by making good use of the index of the character string
filename.rb
s = 'AA'
t = 'abdeeAAbAAAbfde'
result = 0
(0..(t.size - s.size)).each do |i|
substring = t.slice(i, s.size)
if substring == s
result += 1
end
end
puts result
#Expected output ➡︎ 3
#Actual output ➡︎ 3
done!
You can count strings by using it in the string class. Along with the length method (which counts the number of elements when used in the Array class).
If you specify a range with an argument, the character string of that range is returned.
I think the part of "how to cut out the necessary data" is the miso of this time. I think that the part that doesn't come out suddenly is not yet the head to create the algorithm. Hmmm difficult.
Recommended Posts