[Ruby] Search string B from string A (duplicate count)

1 minute read

I want to search for a certain character string from a certain character string I want to search for “s” from the following character strings “t”.


s ='AA'
t ='abdeeAAbAAAbfde'

Normally, I’m a foolish person who thought, “Hey, I can go with the count method.”


s ='AA'
t ='abdeeAAbAAAbfde'
puts t.count(s)

# Expected output ➡︎ 3
# Actual output ➡︎ 5

No, this is just counting the number of A. With the count method, it seems that one character or one character will be searched even if a string of characters is given as an argument.

I want to search for the character string AA because it can be duplicated!

That is,

  1. First AA counting from the left
  2. AAA’s first AA (AA ← this A)
  3. The last AA (A this → AA)

I want to count the above three. (Transferred…!)

What should I do

When chewed and thought, the character string abdeeAAbAAAbfde ab bd de ee eA AA Ab bA AA AA Ab bf fd de Verify if it matches the string AA and count if true, otherwise count false.

※point Use the index of the character string to specify the range

Actual code


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

puts result

# Expected output ➡︎ 3
# Actual output ➡︎ 3


What you need to know

size method

You can count strings by using it in string class. With the length method (counts the number of elements when used in the Array class).

slice method

If the range is specified by the argument, the character string of the range is returned.

Reflection points

I think the point is “how to cut out the necessary data”. I think that the point where it does not come out suddenly is not yet the head of creating algorithms. Mmm it’s difficult.