[RUBY] Search for character string B from character string A (duplicate count)

I want to search for a certain character string from a certain character string

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.

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

In other words

  1. First AA counting from the left
  2. The first AAA of AAA (AA ← this A)
  3. Last AA (A this → AA)

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

What should I do

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

Actual code

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!

What you need to know

size method

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).

slice method

If you specify a range with an argument, the character string of that range is returned.

Reflections

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

Search for character string B from character string A (duplicate count)
Character duplicate count (substring)
[Java] How to erase a specific character from a character string
[Java] How to convert a character string from String type to byte type
A program that searches for a character string, and when the search character string is found, displays the character string from the beginning of the line to just before the search character string.
Search for English words from terminal
[Java] Character judgment / character string formatting (AOJ11 --character count)
Deletes after the specified character from the character string
How to make a judgment method to search for an arbitrary character in an array
[Android] How to convert a character string to resourceId