Menu
Coddy logo textTech

Pattern Finder

Part of the Fundamentals section of Coddy's Swift journey — lesson 85 of 86.

challenge icon

Challenge

Easy

Read two lines of input: the first line is the text to search through, and the second line is the pattern to find.

Count how many times the pattern appears in the text, including overlapping occurrences, and print the count.

Requirements:

  1. Read the text string from the first line of input
  2. Read the pattern string from the second line of input
  3. Iterate through the text and check for the pattern at each position
  4. Count all occurrences, including overlapping matches
  5. Print the total count as a single integer

Hint: To extract a substring starting at index i with a specific length, you can use string slicing with indices. Convert the string to an array of characters or use Swift's string index manipulation to check if the pattern matches at each position.

Example:

If the input is:

ababa
aba

The output should be:

2

The pattern "aba" appears at index 0 and index 2 in "ababa".

Try it yourself

// Read input
let text = readLine()!
let pattern = readLine()!

// TODO: Write your code below
// Count how many times the pattern appears in the text (including overlapping occurrences)


// Output the result
print(count)

All lessons in Fundamentals