Menu
Coddy logo textTech

Pattern Finder

Part of the Fundamentals section of Coddy's R journey — lesson 77 of 78.

challenge icon

Challenge

Easy

Create a function called count_pattern that takes two arguments: text and pattern. The function should return the number of times the pattern appears in the text, including overlapping occurrences.

You will receive two lines of input:

  1. The text string to search in
  2. The pattern string to search for

Call your function with the provided inputs and print the result.

Hints:

  • Use nchar() to get the length of strings
  • Use substr(text, start, stop) to extract substrings
  • Iterate through each valid starting position and check if the substring matches the pattern

For example, if the input is:

ababa
aba

The output should be:

2

Explanation: The pattern "aba" appears at position 1 (ababa) and position 3 (ababa), so the count is 2.

If the input is:

mississippi
issi

The output should be:

2

Try it yourself

# Read input
con <- file("stdin", "r")
text <- suppressWarnings(readLines(con, n = 1))
pattern <- suppressWarnings(readLines(con, n = 1))
close(con)

# TODO: Create a function called count_pattern that takes text and pattern
# and returns the count of overlapping occurrences of pattern in text


# Call the function and print the result
print(count_pattern(text, pattern))

All lessons in Fundamentals